码迷,mamicode.com
首页 > 其他好文 > 详细

和为S的连续正数序列

时间:2017-08-21 12:42:49      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:--   for   swap   return   res   sequence   back   ==   正确答案   

题目描述

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

输出描述:

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

 

class Solution {
public:
    vector<vector<int> > FindContinuousSequence(int sum) {
        vector<vector<int>> allRes;
        int phigh=2,plow=1;
        
        while(phigh > plow) {
            int cur=(phigh +plow)*(phigh-plow +1)/2;
            if(cur<sum)
                phigh++;
            
            if(cur==sum){
                vector<int> res;
                for(int i=plow;i<=phigh;i++)
                    res.push_back(i);
                allRes.push_back(res);
                plow++;
            }
            
            if(cur>sum)
                plow++;
        }
        return allRes;
    }
};

  

(a + b)(b - a + 1) = sum * 2
设x = a + b, y = b - a + 1, y >= 2
枚举y,得x,解出a,b
typedef vector<int> vi;
typedef vector<vi> vvi;
class Solution {
public:
    vvi FindContinuousSequence(int sum) {
        vvi res;
        sum <<= 1;
        for(int i = 2; i * i <= sum; ++i) if(sum % i == 0){
            int j = sum / i, t = (j - i + 1);
            if(!(t & 1)){
                res.push_back(vi());
                vi& v = res[res.size() - 1];
                t >>= 1;
                for(int a = t; a <= j - t; ++a) v.push_back(a);
            }
        }
        for(int i = 0, j = int(res.size()) - 1; i < j; ++i, --j) swap(res[i], res[j]);
        return res;
    }
};

  

 

和为S的连续正数序列

标签:--   for   swap   return   res   sequence   back   ==   正确答案   

原文地址:http://www.cnblogs.com/dd2hm/p/7403549.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!