41.和为S的连续正数序列

题目描述

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

输出描述:

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

题目解答

import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer>> res=new ArrayList<>();
        //两个起点,相当于动态窗口的两边
        int plow=1,phigh=2;
        while(phigh>plow){
            //连续的,差为1的一个序列,求和公式是(a0+an)*n/2
            int cursum=(plow+phigh)*(phigh-plow+1)/2;
            if(cursum==sum){
                ArrayList<Integer> list=new ArrayList<>();
                for(int i=plow;i<=phigh;i++){
                    list.add(i);
                }
                res.add(list);
                plow++;//添加到结果集后左边窗口右移一位
            }else if(cursum<sum){//如果cursum小于sum,那么右边窗口右移一下
                phigh++;
            }else{//如果cursum大于sum,那么左边窗口右移一下
                plow++;
            }
        }
        return res;
    }
}

滑动窗口



posted @ 2019-01-09 20:37  chan_ai_chao  阅读(121)  评论(0编辑  收藏  举报