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) { List<Integer> numList = new ArrayList<>();
StringBuilder sb = new StringBuilder(); dfs(numList, sb, 0, n, k);
int[] res = new int[numList.size()]; for (int i = 0; i < numList.size(); i++) { res[i] = numList.get(i); } return res; }
private void dfs(List<Integer> numList, StringBuilder sb, int index, int n, int k) { if (index == n) { numList.add(Integer.valueOf(sb.toString())); return; }
for (int num = 0; num <= 9; num++) { if (index == 0 && num == 0) { continue; }
if (sb.length() == 0 || Math.abs(num - (sb.charAt(sb.length() - 1) - '0')) == k) { sb.append(num); dfs(numList, sb, index + 1, n, k); sb.deleteCharAt(sb.length() - 1); } } } }
|