Prove safety offer [41] - a continuous and positive sequence S

Title Description

Xiao Ming is very fond of mathematics, one day when he was doing math homework, required to calculate and 9 to 16, he immediately wrote the correct answer is 100. But he was not satisfied with this, he wondered how many kinds of continuous positive number sequence is 100 (including at least two numbers). Before long, he got another set of consecutive positive number and a sequence of 100: 18,19,20,21,22. Now the question to you, you can also quickly identify all positive and continuous sequence S? Good Luck!

Output Description :

输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序

This question can use the idea of dynamic programming algorithm we initialize an array, the array is smaller than sumthe positive number of unique sort the array, we create two pointers leftto the rightpoint of 0, and then create a new variable countrecord from lefta pointer to rightand an array of pointers. Then start whilecycles each comparison countwith sumthe size, if countsmaller, then so right++; if countlarge, will make it left--, then it will equal lefta pointer to rightan array of pointers into the resmiddle. End of the cycle return resto.

function FindContinuousSequence(sum)
{
    let i = 1;
    let temp = new Array(sum-1).fill(1).map(x=>i++)
    let res = [];
    let left = 0;
    let right = 0;
    let count = 0;
    while(right!=sum){
        if(count<sum){
            count += temp[right];
            right++;
        }
        else if(count==sum){
            res.push(temp.slice(left, right));
            count -= temp[left];
            left++;
        }else{
            count -= temp[left];
            left++;
        }
    }
    return res;
}

Guess you like

Origin www.cnblogs.com/Jacob98/p/12580355.html