地址 https://www.acwing.com/problem/content/description/72/spa
輸入一個正數s,打印出全部和爲s的連續正數序列(至少含有兩個數)。指針
例如輸入15,因爲1+2+3+4+5=4+5+6=7+8=15,因此結果打印出3個連續序列1~五、4~6和7~8。code
輸入:15 輸出:[[1,2,3,4,5],[4,5,6],[7,8]]
雙指針指向一個連續空間 若是和小了 則向右擴展 若是和大了 則彈出左邊的值blog
class Solution { public: vector<vector<int> > vv; vector<vector<int> > findContinuousSequence(int sum) { int l = 0; int r = 0; vector<int> nums; for (int i = 1; i <= sum / 2 + 1; i++) { nums.push_back(i); } int tmpSum = nums[l]; while (l < nums.size() && r < nums.size() && l <= r) { if (tmpSum > sum) { tmpSum -= nums[l]; l++; continue; } else if (tmpSum < sum) { tmpSum += nums[r+1]; r++; continue; } else if (tmpSum == sum) { vector<int> v; for (int i = l; i <= r; i++) { v.push_back(nums[i]); } vv.push_back(v); if (r < nums.size() - 1) tmpSum += nums[r + 1]; r++; continue; } } return vv; } };