Original blog post, please indicate the source for reprinting!
# topic
# ideas
Set two auxiliary variables small and big, small represents the minimum value of the sequence, and big represents the maximum value of the sequence. If sum(small ~ big) > s, increase the value of small. If sum(small ~ big) < s , increase the value of big. Since the sequence requires at least two numbers, small increases until (s+1)/2.
# code
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int> > FindContinuousSequence(int sum) { // 结果 vector<vector<int> > res; // special input if (sum< 3 ) return res; // Auxiliary variable int small = 1 ; int big = 2 ; int middle = (sum+ 1 )>> 1 ; while(small < middle) { // count int count =0; for(int i = small;i<=big;++i) count +=i; // if(count == sum) { // 存储结果 vector<int> temp; for(int i = small ;i <= big;++i) { cout<<i<<endl; temp.push_back(i); } res.push_back(temp); ++small; ++big; } if(count<sum) ++big; else ++small; } return res; } }; intmain () { int sum = 100 ; Solution solution; solution.FindContinuousSequence(sum); return 0; }