[LeetCode: Recursion and Backtracking]: 1291. Order times

1291.Shun frequency

Difficulty: medium


We define the "order of order" as: the number on each digit is an integer that is 1 greater than the number on the previous digit.
Please return an ordered list (sorted from smallest to largest) consisting of all the order numbers in the range of [low, high].

Example 1:

Output: low = 100, high = 300
Output: [123,234]
Example 2:

Output: low = 1000, high = 13000
Output: [1234,2345,3456,4567,5678,6789,12345]

prompt:

10 <= low <= high <= 10^9


answer

方法一:穷举
/**
 * @param {number} shorter
 * @param {number} longer
 * @param {number} k
 * @return {number[]}
 */
var sequentialDigits = function(low, high) {
    
    
let res = [],
        index = 0;
    for (let i = 1; i <= 9; i++) {
    
    
        let n = i;
        for (let j = i + 1; j <= 9; j++) {
    
    
            n = n * 10 + j;
            if (n >= low && n <= high) {
    
    
                res[index++] = n;
            }
        }
    }
    //由于穷举后的数并不是由小到大,所以需要进行排序
    return res.sort(function(a,b){
    
    return a-b;});
};

方法二:剪枝
var sequentialDigits = function(low, high) {
    
    
    let res = []
    let lowLen = low.toString().length
    let highLen = high.toString().length
    for(let i=lowLen;i<=highLen;i++){
    
    
        for(let j=1;j<=10-i;j++){
    
    //剪枝:首位数不会大于10-i
            let str = ''
            let num = j
            str += num
            let k = i-1
            while(k--){
    
    
                num++
                str += num
            }
            let ans = parseInt(str)
            if(ans>=low && ans<=high){
    
    
                res.push(ans)
            }
        }
    }
    return res    
};


analysis

It can be seen from the question that the number of digits is one digit greater than the previous digit. If you want to meet the definition domain, you can use the exhaustive method to traverse and enter the array if you meet the conditions, because the number entered is not from small to large Yes, so it needs to be sorted at the end.
Although the exhaustive method is simple, it is too time-consuming. Pruning can also be done here.

If you want to output the sequence number of [100,1000], first use toString().length to convert the number to a string and then find the length, that is, the number of digits in the data can be reached, where 100 is 3 digits and 1000 is 4 digits Number, that is, i>=3&&i<=4.
There are three digits between 100-1000, and the largest number of matching orders is 789, and there are no subsequent ones, that is, 789 with the first digit of 7 exists, and the first 8.9 does not exist, so there is no need Traverse, so it can be pruned, for this 10-3(i)=7.

Guess you like

Origin blog.csdn.net/qq_43522998/article/details/113086846