《剑指offer》和为S的连续正数序列

本题来自《剑指offer》 和为S的连续正数序列

题目:

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

思路:

   从1和2开始算起,两个指针同时遍历,

  如果当前的求和值小于目标值,那么就将大值加入,

  如果大于就将小值加入

  如果等于就从小到大这个序列保存起来。

C++ Code:

class Solution {
public:
    vector<vector<int> > FindContinuousSequence(int sum) {
        int small = 1;                                //small point,that value equal 1
        int big = 2;                                  //big point,that value equal 2
        int middle = (1+sum)/2;                       //middle point
        int cursum = small + big;                     //current sum value
        vector<vector<int> > result;                  //result container
        while(small<middle){
            if(cursum == sum){                        //if cursum equal sum
                vector<int> res;                      //temp container
                for (int i=small;i<=big;i++){         //save temp value
                    res.push_back(i);
                }
                result.push_back(res);
            }
            while(cursum>sum&&small<middle){         //if cursum small sum
                cursum -= small;                     //remove small
                small ++;                            //small increase
                if (cursum==sum){                    //cursum equal sum
                    vector<int> res;
                    for (int i=small;i<=big;i++){    //save temp value
                        res.push_back(i);
                    }
                    result.push_back(res);
                }
            }
            big ++;                                 //if cursum small sum,that big increase
            cursum += big;                    
        }
        return result;
    }
};

Python Code:

# -*- coding:utf-8 -*-
class Solution:
    def FindContinuousSequence(self, tsum):
        # write code here
        result = []
        for i in range(1,tsum//2+1):        #从1开始计算,到tsum的一半结束
            j = i
            sum = 0
            s1 = []
            while sum < tsum :
                sum += j
                s1.append(j)                #每次将数存放在列表中
                if sum == tsum:             #只有当相等时候就将其放到结果列表中
                    result.append(s1)
                else:
                    j += 1                  #否则就继续循环
        return result
posted @ 2019-04-28 14:21  weilongyitian  阅读(172)  评论(0编辑  收藏  举报