本文共 692 字,大约阅读时间需要 2 分钟。
Q:输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9输出:[[2,3,4],[4,5]]
class Solution: def findContinuousSequence(self, target: int) -> List[List[int]]: res = [] # 从1开始,依次遍历到target,求和,与target判断大小,符合条件的元素放入临时数组中 for i in range(1,target): ls = [] temp = i ls.append(i) for j in range(i+1,target): temp += j if temp < target: ls.append(j) elif temp == target: ls.append(j) res.append(ls) break else: break return res
转载地址:http://mejui.baihongyu.com/