# 连续差相同的数字 - Numbers With Same Consecutive Differences

[递归]

​ 返回所有长度为 `N` 且满足其每两个连续位上的数字之间的差的绝对值为 `K`非负整数。​ 请注意，除了数字 `0` 本身之外，答案中的每个数字都不能有前导零。例如，`01` 因为有一个前导零，所以是无效的；但 `0` 是有效的。​ 你可以按任何顺序返回答案。

``````输入：N = 3, K = 7

``````

``````输入：N = 2, K = 1

``````

## solution

### My solution

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 `````` ``````class Solution { public int[] numsSameConsecDiff(int N, int K) { int current_bit = 1; int current_num = 0; Stack stack = new Stack(); if(N==1) stack.push(0); int bit = N; for (int i = 1; i < 10; i++) { current_bit = i; current_num = 0; solve(stack, N, K, current_bit, current_num, bit); } int[] result = new int[stack.size()]; int index = 0; while (!stack.isEmpty()) result[index++] = stack.pop(); System.out.println(Arrays.toString(result)); return result; } public void solve(Stack stack, int N, int K, int current_bit, int current_num, int bit) { current_num += current_bit * (int) Math.pow(10, --bit); if (bit == 0) { stack.push(current_num); return; } if (current_bit + K <= 9) solve(stack, N, K, current_bit + K, current_num, bit); if (K != 0 && current_bit - K >= 0) solve(stack, N, K, current_bit - K, current_num, bit); } } ``````

### Other Solution

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 `````` ``````class Solution { public: void dfs(int N, int K, int last, int rate, vector &ans){ if (N==0) { ans.push_back(rate); return; } if (last==-1) { for (int x=1; x<=9; x++) dfs(N-1, K, x, rate*10+x, ans); }else{ if (last-K>=0) dfs(N-1, K, last-K, rate*10+last-K, ans); if (K!=0 && last+K<=9) dfs(N-1, K, last+K, rate*10+last+K, ans); } } vector numsSameConsecDiff(int N, int K) { vector ans; ans.clear(); if (N==1) { for (int i=0; i<10; i++) ans.push_back(i); return ans; } dfs(N, K, -1, 0, ans); return ans; } }; ``````