题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
方法一:
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
int l = 1,r = 1,sumx = 1;
vector<vector<int> > ans;
while(l <= r){
r ++;
sumx += r;
while(sumx > sum){
sumx -= l;
l ++;
}
if(sumx == sum && l != r){
vector<int> tmp;
for(int i = l;i <= r;i ++) tmp.push_back(i);
ans.push_back(tmp);
}
}
return ans;
}
};
方法二:
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
vector<vector<int> > res;
if(sum<3)
return res;
int small=1,big=2;
while(small<(sum+1)/2){
int i,amount=0;
for(i=small;i<=big;i++)
amount+=i;
if(amount<sum)
big++;
else if(amount>sum)
small++;
else{
vector<int> temp;
for(i=small;i<=big;i++)
temp.push_back(i);
res.push_back(temp);
small++;
big++;
}
}
return res;
}
};
方法三:
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum)
{
vector<vector<int>> v;
vector<int> tmp;
int small=1;
int big=2;
int mid=(sum+1)/2;
int CurSum=small+big;
while(small<mid)
{
if(sum==CurSum)
{
tmp.clear();
for(int i=small;i<=big;i++)
{
tmp.push_back(i);
}
v.push_back(tmp);
}
while(CurSum>sum&&small<mid)
{
CurSum-=small;
small++;
if(CurSum==sum)
{
tmp.clear();
for(int i=small;i<=big;i++)
{
tmp.push_back(i);
}
v.push_back(tmp);
}
}
big++;
CurSum+=big;
}
return v;
}
};
网友评论