输入一个正整数 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
sliding window+剪枝
class Solution { public int[][] findContinuousSequence(int target) { List<int[]> list=new ArrayList<>(); for(int l=1,r=1,sum=0;r<target/2+2;r++){ sum+=r; while(sum>target){ sum-=l; l++; } if(sum==target){ int[] window=new int[r-l+1]; for(int i=0;i<r-l+1;i++){ window[i]=l+i; } list.add(window); if(window.length==2) break; } } int[][] res=new int[list.size()][]; for(int i=0;i<res.length;i++){ res[i]=list.get(i); } return res; } }
2 pointer
class Solution(object): def findContinuousSequence(self, target): """ :type target: int :rtype: List[List[int]] """ res=[] l=1 r=2 while l<r: sum=(l+r)*(r-l+1)/2 if sum<target: r+=1 elif sum>target: l+=1 else: res.append([i for i in range(l,r+1)]) l+=1 r+=1 return res