class Solution {
public:
void dfs(vector<int>& ans,int fa,long long path,int K,int& low,int& high,bool flag){
if(K==0){
if(path >= low && path <= high) ans.push_back(path);
return ;
}
if(flag){
dfs(ans,0,path*10,K-1,low,high,true);
for(int i=1;i<10;i++) dfs(ans,i,path*10+i,K-1,low,high,false);
return ;
}
if(fa-1 >= 0) dfs(ans,fa-1,path*10+fa-1,K-1,low,high,false);
if(fa+1 <= 9) dfs(ans,fa+1,path*10+fa+1,K-1,low,high,false);
}
vector<int> countSteppingNumbers(int low, int high) {
vector<int> ans;
int t = high;
int K = 0; //high的长度
while(t>0){K++;t/=10;}
dfs(ans,0,0,K,low,high,true);
return ans;
}
};
No.128 - LeetCode1215 - 数位相差为1的数字
最新推荐文章于 2025-05-07 15:46:24 发布
本文介绍了一种使用递归深度优先搜索(DFS)算法来解决寻找特定范围内阶梯数字的问题。通过定义一个Solution类,其中包含dfs和countSteppingNumbers两个主要函数,实现了从low到high范围内的所有阶梯数字的查找。该算法首先确定高位数字,然后递归地构造后续位数,确保相邻位之间的差不超过1,从而找出所有符合条件的阶梯数字。
1317

被折叠的 条评论
为什么被折叠?



