和为S的连续正数序列

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

思路:要想连续和等于sum,那么起始值一定小于sum/2,比如sum=20,那么10+11很明显就大于20,所范围就是1到sum/2,然后遍历找符合条件的。。。(但个人认为复杂度略高。。。。。。)

public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
             ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
            if(sum<2) return res;
            
            for(int i = 1; i <= sum/2 ; i++ ){
                ArrayList<Integer> temp = new ArrayList<Integer>();
                int count=0;
                for(int j=i; j < sum ;j++){
                    count+=j;
                    temp.add(j);
                    if(count > sum)
                        break;
                    else if(count==sum){
                        res.add(temp);
                        break;
                    }
                  
                }
            }
        return res;
    }

 

posted @ 2017-04-11 00:49  雪浪snowWave  阅读(142)  评论(0编辑  收藏  举报