题目描述:
找到所有和为S的连续整数序列,序列长度>=2
思路:
滑动窗口,维护序列的最小值和最大值。如果当前序列和大于sum,最小值向右移动,反之,最大值向右移动。
好像还有很多解法。。
代码:
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
if (sum <= 1) return {};
int low = 1;
int high = low+1;
int tsum = low + high;
vector<int> temp;
vector<vector<int> >ans;
while(low < sum) {
if (tsum == sum) {
temp.clear();
for (int i=low; i<=high; ++i) {
temp.push_back(i);
}
ans.push_back(temp);
}
if (tsum <= sum) {
high += 1;
tsum += high;
}
if (tsum > sum) {
tsum -= low;
low += 1;
}
}
return ans;
}
};