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

第一种解法是小生直接上手的,代码有点丑。剩下两种是吸收大家的灵感而来。

1.穷举法a

function FindContinuousSequence(sum) {
    const result = []
    for (let n = 2; n <= Math.ceil((Math.sqrt(8 * sum + 1) - 1) / 2); n++) {
        let arr = []
        let [arr_sum, start, len] = [0, 1, n]
        while (len--) {
            arr_sum += start
            arr.push(start++)
        }
        for (let i = start; i <= sum; i++) {
            if (arr_sum === sum) result.unshift(JSON.parse(JSON.stringify(arr)))
            arr_sum = arr_sum + i - arr.shift()
            arr.push(i)
        }
    }
    return result
}

2.穷举法b

function FindContinuousSequence(sum) {
    if(sum===1)return [];
    const result = []
    for (let n = 1; n <sum-1 ; n++) {
        let [num,buf] = [0,n]
        while (num <sum){
            num+=buf
            buf++
        }
        if(num === sum){
            let arr = []
            while (--buf>=n) arr.unshift(buf)
            result.push(arr)
        }
    }
    return result
}

3.双指针法

function FindContinuousSequence(sum) {
    const result = []
    let [start, end] = [1, 2]
    while (start < end) {
        let count = (start + end) * (end - start + 1) / 2;
        if (count < sum) end++
         else if (count > sum) start++
         else {
            let arr = []
            for (let i = start; i <= end; i++) arr.push(i)
            result.push(arr)
            start++
        }
    }
    return result
}