1291. Sequential Digits

问题:

给定一个范围[low, high],

求所有在这个范围的数(从小到大排序后的),要求:这些数的后一位数字比前一位数字大一。

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

  

解法:Backtracking(回溯算法)

  • 状态:到当前位为止,构成的数字。
  • 选择:
    • 第一位:1~9
    • 其他位:前一位+1
  • 递归退出条件:
    • path>high or path的即将加入的下一位数字>9
  • 加入res条件:所得数字path属于[low, high]
    • ⚠️  注意:这里加入res,并不=退出递归。

⚠️ 注意:由于本题需要返回有序的结果,最后需要对res 进行排序。sort(res.begin(), res.end());

代码参考:

 1 class Solution {
 2 public:
 3     void backtrack(vector<int>& res, int path, int nxtdigit, int low, int high) {
 4         if(path>=low && path<=high) {
 5             res.push_back(path);
 6         }
 7         if(path>high || nxtdigit>9) {
 8             return;
 9         }
10         int cur = 0;
11         if(path==0) {
12             for(int i=nxtdigit; i<=9; i++) {
13                 cur = path*10+i;
14                 if(cur <= high) {
15                     backtrack(res, cur, i+1, low, high);
16                 } else break;
17             }
18         } else {
19             cur = path*10+nxtdigit;
20             if(cur <=high) backtrack(res, cur, nxtdigit+1, low, high);
21             else return;
22         }
23         return;
24     }
25     vector<int> sequentialDigits(int low, int high) {
26         vector<int> res;
27         backtrack(res, 0, 1, low, high);
28         sort(res.begin(), res.end());
29         return res;
30     }
31 };

 

posted @ 2021-02-01 15:53  habibah_chang  阅读(74)  评论(0编辑  收藏  举报