Skip to the content.

leetcode [面试题57 II] 和为s的连续正数序列


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。

序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。

示例 1:

输入:target = 9
输出:[[2,3,4],[4,5]]

示例 2:

输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]

限制:

1 <= target <= 10^5
class Solution:
    def findContinuousSequence(self, target: int) -> List[List[int]]:
        ans = []
        window = []
        sumval = 0
        for i in range(1, (target + 1) // 2 + 1):
            window.append(i)
            sumval += i
            
            while sumval >= target and len(window) > 0:
                if sumval == target:
                    ans.append(window.copy())
                tmp = window.pop(0)
                sumval -= tmp
        return ans