No.128 - LeetCode1215 - 数位相差为1的数字

本文介绍了一种使用递归深度优先搜索(DFS)算法来解决寻找特定范围内阶梯数字的问题。通过定义一个Solution类,其中包含dfs和countSteppingNumbers两个主要函数,实现了从low到high范围内的所有阶梯数字的查找。该算法首先确定高位数字,然后递归地构造后续位数,确保相邻位之间的差不超过1,从而找出所有符合条件的阶梯数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值