leetcode1291. 顺次数(回溯)

我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。

请你返回由 [low, high] 范围内所有顺次数组成的 有序 列表(从小到大排序)。

示例 1:

输出:low = 100, high = 300
输出:[123,234]

代码

class Solution {
    List<Integer> cList=new ArrayList<>();
    public List<Integer> sequentialDigits(int low, int high) {

        for(int i=1;i<10;i++)//以不同数字开头
        {
            sequential(low,high,i,i);
        }
        Collections.sort(cList);排序
        return cList;
    }

    public void sequential(int low, int high,int pre,int sum) {
        if(pre>9) return;//不能再递增1了
        if(sum>high) return;//数字太大了
        if(sum>=low) {//满足条件
            cList.add(sum);
   
        }
        sequential(low, high, pre+1, sum*10+pre+1);下一位

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44560620/article/details/107751899