和为S的连续正数序列

题目描述

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

返回值描述:

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

从1到sum/2进行穷举计算
class Solution {
public:
    vector<vector<int> > FindContinuousSequence(int sum) {
        vector<vector<int> > result;
        if(sum <= 1) return result;
        int halfSum = sum / 2;
        vector<int> temp;
        int tempSum = 0;
        int k ;
        for(int i=1;i<=halfSum;i++){
            k = i;
            while(tempSum<sum){
                temp.push_back(k);
                tempSum+=k;
                k++;
            }
            if(tempSum == sum){
                result.push_back(temp);
                
            }
            tempSum = 0;
            temp.clear();
        }
        return result;
    }
};

java 实现:

利用双指针,产生了一个滑动窗口,通过对比滑动窗口中所有数字的和与sum的关系,来改变双指针的指向

import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer> >();
        if(sum <= 2) return result;
        int low = 1;
        int high = 2;
        int half = (sum+1) / 2;int tempsum = low + high;
        
        while(high <= half){
            if(tempsum < sum){
                high++;
                tempsum += high;
            }else if(tempsum > sum){
                tempsum -= low;
                low++;
            }else{
                ArrayList<Integer> temp = new ArrayList<>();
                for(int i = low;i<=high;i++){
                    temp.add(i);
                }
                result.add(temp);
                tempsum -= low;
                low++;
                high++;
                tempsum += high;
            }
        }
        return result;
    }
}

 上述算法是使用tempsum 进行了一个临时求和比较,当然也可以使用等差数列求和公式直接计算

原文地址:https://www.cnblogs.com/ttzz/p/13928645.html