输入一个正整数 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution(object):
def findContinuousSequence(self, target):
"""
:type target: int
:rtype: List[List[int]]
"""
i=1
j=2
sum=1
res=[]
while i<(target+1)//2:
if sum<target:
sum+=j
j+=1
elif sum>target:
sum-=i
i+=1
else:
res.append(list(range(i,j)))
sum-=i
i+=1
return res
执行结果:
通过
显示详情
执行用时 :84 ms, 在所有 Python 提交中击败了64.96%的用户
内存消耗 :12.7 MB, 在所有 Python 提交中击败了100.00%的用户