小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
vector<vector<int> > allRes;
int phigh = 2,plow = 1; //定义一个大指针一个小指针
while(phigh > plow){
int cur = (phigh + plow) * (phigh - plow + 1) / 2; //求两个指针中间的数的和
if( cur < sum) //如果和小于期望值,大指针右移一个数
phigh++;
if( cur == sum){ //如果求和等于期望值,存入结果
vector<int> res;
for(int i = plow; i<=phigh; i++)
res.push_back(i);
allRes.push_back(res);
plow++;
}
if(cur > sum) //如果和大于期望值,小指针右移一个数
plow++;
}
return allRes;
}
};