1291. Sequential Digits

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.

Example 1:

``````Input: low = 100, high = 300
Output: [123,234]
``````

Example 2:

``````Input: low = 1000, high = 13000
Output: [1234,2345,3456,4567,5678,6789,12345]
``````

Constraints:

• `10 <= low <= high <= 10^9`

``````class Solution {
public:
vector<int> sequentialDigits(int low, int high) {
vector<int> res;
queue<int> q;
for (int i = 1; i <= 9; ++i) q.push(i);
while (!q.empty()) {
int num = q.front(); q.pop();
if (num >= low && num <= high) res.push_back(num);
if (num > high) break;
int d = num % 10;
if (d < 9) q.push(num * 10 + d + 1);
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> sequentialDigits(int low, int high) {
vector<int> res;
for (int i = 1; i <= 9; ++i) {
int next = i, num = i;
while (num <= high && next < 10) {
if (num >= low) res.push_back(num);
num = num * 10 + ++next;
}
}
sort(res.begin(), res.end());
return res;
}
};
``````

``````class Solution {
public:
vector<int> sequentialDigits(int low, int high) {
vector<int> res;
for (int i = 1; i <= 9; ++i) {
dfs(low, high, i, 0, res);
}
sort(res.begin(), res.end());
return res;
}
void dfs(int low, int high, int digit, int num, vector<int>& res) {
if (num >= low && num <= high) res.push_back(num);
if (num > high || digit > 9) return;
dfs(low, high, digit + 1, num * 10 + digit, res);
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1291

https://leetcode.com/problems/sequential-digits/

https://leetcode.com/problems/sequential-digits/discuss/451862/C%2B%2B-BFS

https://leetcode.com/problems/sequential-digits/discuss/451849/JavaPython-3-Simple-codes.

https://leetcode.com/problems/sequential-digits/discuss/1711942/C%2B%2B-DFS-with-diagram-or-Basic-0-ms

LeetCode All in One 题目讲解汇总(持续更新中…)

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation