劍指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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章