题意
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]
问题分析
双指针
//C++
class Solution {
public:
vector<vector<int>> findContinuousSequence(int target){
vector<vector<int>> res;
if(target < 3)
return res;
int small = 1;
int big = 2;
int mid = (1+target)/2;
int sum = small + big;
while(small < mid){
if(sum == target){
vector<int> tmp;
for(int num = small; num <= big; num++){
tmp.push_back(num);
}
res.push_back(tmp);
sum += ++big;
}
else if(sum < target){
sum += ++big;
}
else{
sum -= small++;
}
}
return res;
}
};