剑指Offer——和为S的连续正数序列

题目描述

小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

输出描述:

输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序

题解
#include <iostream>
#include <vector>

using namespace std;

vector<vector<int> > FindContinuousSequence(int sum) {
    vector<vector<int> > res;
    int low = 1, high = 2;
    while (low < high) {
        int tempsum = ((low + high) * (high - low + 1) >> 1);
        if (tempsum == sum) {
            vector<int> temp;
            for (int i = low; i <= high; i++)
                temp.push_back(i);
            res.push_back(temp);
            low++;
        } else if (tempsum < sum)
            high++;
        else
            low++;
    }
    return res;
}

int main() {
    ios::sync_with_stdio(false);
    int sum;
    vector<vector<int> > res;
    vector<int> temp;
    cin >> sum;
    res = FindContinuousSequence(sum);
    vector<vector<int> >::iterator iter;
    vector<int>::iterator it;
    for (iter = res.begin(); iter != res.end(); iter++) {
        temp = *iter;
        for (it = temp.begin(); it != temp.end(); it++)
            cout << *it << " ";
        cout << endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值