2019南京大学计算机考研复试机试题-Stepping Numbers

stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1.

  • For example, 321 is a stepping number while 421 is not.

Given two integers low and high, return a sorted list of all the stepping numbers in the inclusive range [low, high].

Example 1:

Input: low = 0, high = 21
Output: [0,1,2,3,4,5,6,7,8,9,10,12,21]

Example 2:

Input: low = 10, high = 15
Output: [10,12]
class Solution {
public:
    vector<int> countSteppingNumbers(int low, int high) {
        vector<int> res;
        for(int i = 1;i <10;i ++){
            dfs(res,i,i,high);
        }
        vector<int> ans;
        if(low == 0)
            ans.push_back(0);
        for(auto i:res){
            if(i >= low && i <= high)
                ans.push_back(i);
        }
        sort(ans.begin(),ans.end());
        return ans;

    }
    void dfs(vector<int>&v,long num,long lastnum,long high){
        if(num > high)
            return;
        v.push_back(num);
        if(lastnum!=9)
            dfs(v,num*10+lastnum+1,lastnum+1,high);
        if(lastnum!=0)
            dfs(v,num*10+lastnum-1,lastnum-1,high);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值