描述:给定一个和S,找出和为S的连续序列,如9:[2,3,4], [4,5]
分析:网上许多方法中,印象最深刻的是双指针法。两个指针限定区间的范围和大小。
vector<vector<int>> CumSum(int S)
{
vector<vector<int>> res;
vector<int>temp;
int low = 1, high = 2;
while(low<high)
{
// 计算当前区间的和
int cur_sum = (low+high)*(high-low+1)/2;
if(cur_sum == S)
{
for(int I = low; I<= high; I++)
temp.push_back(i);
res.push_back(temp);
temp.clear();
low++;
}
else
if(cur_sum < S)
// 区间和比S小,右边界右移,扩
high++;
else
// 区间和比S大,左边界右移,缩
low++;
}
return res;
}