【剑指Offer-57-II】和为s的连续正数序列
问题
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例
输入: target = 15
输出: [[1,2,3,4,5],[4,5,6],[7,8]]
解答
class Solution {
public:
vector<vector<int>> findContinuousSequence(int target) {
int sum = 0, left = 1, right = 1;
vector<vector<int>> res;
while (right <= (target + 1) >> 1) {
sum += right++;
while (sum > target) sum -= left++;
if (sum == target) {
vector<int> ans;
for (int i = left; i < right; i++) ans.push_back(i);
res.push_back(ans);
}
}
return res;
}
};