题目:输出所有和为S的连续正数序列。序列内按照从小到大的顺序,序列间按照开始数字从小到大的顺序.
思路:利用求和公式:(首项+尾项)*项数/2,对连续正数序列求和。跟和为s的两个数字的题目思路相同,定义两个指针:int begin;int end = 2作为初始条件,while(begin<end && end<sum)(如果end的值已经是sum,则就没有再向后计算的必要了,因为无论如何都会大于sum),int curSum = (begin+end)*(end-begin)/2,if(curSum < sum),向后移动end(end++);if(curSum > sum),向后移动begin(begin++);if(curSum == sum),定义容器temp,将从begin到end的所有数字存到容器中,begin++。
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
vector<vector<int>> result;
int begin = 1;
int end = 2;
while(begin < end && end < sum){
int current = (begin + end)*(end - begin + 1)/2;
if(current == sum){
vector<int> temp;
for(int i=begin; i<=end; i++)
temp.push_back(i);
result.push_back(temp);
begin++;
}
if(current < sum)
end++;
if(current > sum)
begin++;
}
return result;
}
};