Участник:UlitinAleksander/numbers-with-same-consecutive-differences

Материал из DISCOPAL
Перейти к: навигация, поиск

Java

https://leetcode.com/problems/numbers-with-same-consecutive-differences/

class Solution {
    public int[] numsSameConsecDiff(int N, int K) {
        Set<Integer> combinations = new HashSet<>();
        int i = N == 1 ? 0 : 1;
        for (; i < 10; i++) {
            recursion(N - 1, K, i, combinations);
        }
        int[] answer = new int[combinations.size()];
        i = 0;
        for (int num : combinations) {
            answer[i++] = num;
        }
 
        return answer;
    }
 
    private static void recursion(int n, int k, int currentNum, Set<Integer> combos) {
        if (n == 0) {
            combos.add(currentNum);
        }
        else {
            if (currentNum % 10 + k < 10) {
                recursion(n - 1, k, (currentNum * 10 + (currentNum % 10 + k)), combos);
            }
            if (currentNum % 10 - k >= 0) {
                recursion(n - 1, k, (currentNum * 10 + (currentNum % 10 - k)), combos);
            }
        }
    }
}