输入一个正整数 target
,输出所有和为 target
的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9 输出:[[2,3,4],[4,5]]
示例 2:
输入:target = 15 输出:[[1,2,3,4,5],[4,5,6],[7,8]]
限制:
1 <= target <= 10^5
解析:
前缀和 + 双指针
class Solution { public: vector<int> presum; vector<vector<int>> findContinuousSequence(int target) { presum.push_back(0); vector<vector<int> > ret; for(int i = 1; i <= 100000 / 2; i++) { presum.push_back(presum[i - 1] + i); } int p = 1, q = 1; while(p < presum.size() && q < presum.size()) { int diff = presum[q] - presum[p - 1]; if(diff == target && q - p > 0) { vector<int> temp; for(int i = p; i <= q; i++) temp.push_back(i); ret.push_back(temp); q++; } else if(diff < target) q++; else p++; } return ret; } };