题目描述
- 输入一个正数 s,打印出所有和为 s 的
连续正数序列
(至少含有两个数)
- 例如,输入 15,由于 1+2+3+4+5 = 4+5+6 = 7+8 = 15,所以打印出 3 个连续序列 1 ~ 5,4 ~ 6,7 ~ 8
题目解读
代码
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
int left = 1;
int right = 2;
int middle = (1 + sum) / 2;
int toSum = left + right;
vector<vector<int> > data;
while(left < middle){
if(toSum == sum){
data.push_back(core(left, right));
}
while(toSum > sum && left < middle){
toSum = toSum - left;
left ++;
if(toSum == sum){
data.push_back(core(left, right));
}
}
right ++;
toSum = toSum + right;
}
return data;
}
vector<int> core(int left, int right){
vector<int> data;
for(int i= left; i <= right; i++){
data.push_back(i);
}
return data;
}
};
int main(){
Solution ss;
vector<vector<int> > data = ss.FindContinuousSequence(15);
for(int i=0; i < data.size(); i++){
for(int j=0; j < data[i].size(); j++){
cout<<data[i][j]<<" ";
}
cout<<endl;
}
}
总结展望