题目描述
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
分析
使用两个标志位,如果从开头到结尾的和大于目标数字,结尾+1,如果小于,开头+1,直到到N/2为止
代码实现
vector<vector<int> > FindContinuousSequence(int sum) {
vector<vector<int>>res_all;
if(sum<=0)
return res_all;
int start=1,end=1;
int total = 1;
while(end<=(1+sum)/2){
if(total<sum){
end++;
total+=end;
}
else if(total>sum){
total-=start;
start++;
}
else if(total ==sum ){
if( start==end ){
end++;
total+=end;
continue;
}
vector<int>res;
for(int i=start;i<=end;i++)
res.push_back(i);
res_all.push_back(res);
end++;
total+=end;
}
}
return res_all;
}