|
1 | 1 | class 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 |
| - Set<Integer> set = new HashSet<>(); |
7 |
| - for (int i = 1; i <= 9; i++) { |
8 |
| - helper(i, new StringBuilder(), K, set, N); |
9 |
| - } |
10 |
| - int[] ans = new int[set.size()]; |
11 |
| - Iterator<Integer> iterator = set.iterator(); |
12 |
| - for (int i = 0; i < ans.length; i++) { |
13 |
| - ans[i] = iterator.next(); |
14 |
| - } |
15 |
| - return ans; |
| 2 | + public int[] numsSameConsecDiff(int n, int k) { |
| 3 | + List<Integer> result = new ArrayList<>(); |
| 4 | + helper(n, k, result, new StringBuilder()); |
| 5 | + return result.stream().mapToInt(Integer::intValue).toArray(); |
16 | 6 | }
|
17 | 7 |
|
18 |
| - private void helper(int curr, StringBuilder sb, int k, Set<Integer> set, int n) { |
| 8 | + private void helper(int n, int k, List<Integer> result, StringBuilder sb) { |
19 | 9 | if (sb.length() == n) {
|
20 |
| - set.add(Integer.parseInt(sb.toString())); |
21 |
| - } |
22 |
| - if (sb.length() > n || curr > 9 || curr < 0) { |
| 10 | + result.add(Integer.parseInt(sb.toString())); |
23 | 11 | return;
|
24 | 12 | }
|
25 |
| - else { |
26 |
| - sb.append(curr); |
27 |
| - helper(curr + k, sb, k, set, n); |
28 |
| - helper(curr - k, sb, k, set, n); |
| 13 | + for (int i = 0; i <= 9; i++) { |
| 14 | + if (sb.isEmpty() && i == 0) { |
| 15 | + continue; |
| 16 | + } |
| 17 | + if (!sb.isEmpty() |
| 18 | + && Math.abs(Character.getNumericValue(sb.charAt(sb.length() - 1)) - i) != k) { |
| 19 | + continue; |
| 20 | + } |
| 21 | + sb.append(i); |
| 22 | + helper(n, k, result, new StringBuilder(sb)); |
29 | 23 | sb.deleteCharAt(sb.length() - 1);
|
30 | 24 | }
|
31 | 25 | }
|
|
0 commit comments