-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSequentialDigits.java
More file actions
67 lines (52 loc) · 1.96 KB
/
Copy pathSequentialDigits.java
File metadata and controls
67 lines (52 loc) · 1.96 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
// Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
// See: https://leetcode.com/problems/sequential-digits/
// See: https://leetcode.com/problems/sequential-digits/discuss/613365/Java-Two-simple-solutions
package leetcode.backtracking;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class SequentialDigits {
/**
* Recursive solution.
*/
public List<Integer> sequentialDigits(int low, int high) {
List<Integer> ans = new LinkedList<Integer>();
for (int i = 1; i < 10; i++)
recur(low, high, i, i + 1, ans);
Collections.sort(ans);
return ans;
}
private void recur(int lo, int hi, int currNum, int lastDigit, List<Integer> ans) {
if (currNum > hi)
return;
if (lastDigit <= 10) {
if (currNum >= lo && currNum <= hi)
ans.add(currNum);
recur(lo, hi, currNum * 10 + lastDigit, lastDigit + 1, ans);
}
}
/*
* Iterative solution.
*/
public List<Integer> sequentialDigits_iter(int low, int high) {
List<Integer> ans = new LinkedList<Integer>();
for (int start = 1; start < 10; start++) {
int curr = start;
int last = curr + 1;
while (curr <= high && last <= 10) {
if (curr >= low)
ans.add(curr);
curr = curr * 10 + last;
last++;
}
}
Collections.sort(ans);
return ans;
}
public static void main(String[] args) {
SequentialDigits sln = new SequentialDigits();
System.out.println(sln.sequentialDigits(1000, 13000));
System.out.println(sln.sequentialDigits(100, 300));
}
}