Approach
Depth-first search
For Numbers With Same Consecutive Differences, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 35 lines of Java from the credited upstream file 967.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] numsSameConsecDiff(int n, int k) {3 if (n == 1)4 return new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};5 6 List<Integer> ans = new ArrayList<>();7 8 if (k == 0) {9 for (char c = '1'; c <= '9'; ++c) {10 final String s = String.valueOf(c).repeat(n);11 ans.add(Integer.parseInt(s));12 }13 return ans.stream().mapToInt(Integer::intValue).toArray();14 }15 16 for (int num = 1; num <= 9; ++num)17 dfs(n - 1, k, num, ans);18 19 return ans.stream().mapToInt(Integer::intValue).toArray();20 }21 22 private void dfs(int n, int k, int num, List<Integer> ans) {23 if (n == 0) {24 ans.add(num);25 return;26 }27 28 final int lastDigit = num % 10;29 30 for (final int nextDigit : new int[] {lastDigit - k, lastDigit + k})31 if (0 <= nextDigit && nextDigit <= 9)32 dfs(n - 1, k, num * 10 + nextDigit, ans);33 }34}35