【剑指offer】 和为s的连续正数序列,C++实现

原创博文,转载请注明出处!

# 题目

image

# 思路

      设置两个辅助变量small和big,small表示序列的最小值,big表示序列的最大值。如果sum(small ~ big) > s,则增大small的值。如果sum(small ~ big)  <  s ,则增大big的值。因为序列要求至少两个数字,所以small增加到(s+1)/2为止。

image

# 代码

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    vector<vector<int> > FindContinuousSequence(int sum) {

        // 结果
        vector<vector<int> > res;

        // 特殊输入
        if(sum<3)
            return res;

        // 辅助变量
        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;
    }
};
int main()
{
    int sum = 100;
    Solution solution;
    solution.FindContinuousSequence(sum);
    return 0;
}
posted @ 2018-04-30 13:59  wanglei5205  阅读(342)  评论(0编辑  收藏  举报
levels of contents