41和为S的连续正数序列

题目描述

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

输出描述:

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



类似于上一题的夹逼

 1 import java.util.ArrayList;
 2 public class Solution {
 3     public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
 4         ArrayList<ArrayList<Integer>>  res  =  new ArrayList<ArrayList<Integer>>();
 5         int small = 1,big =2;
 6         while(small!=(1+sum/2)){
 7            int  my_sum = sumlist(small,big);
 8             if(my_sum==sum){
 9                 ArrayList<Integer> temp = new ArrayList<Integer>();
10                 for(int i = small;i<=big;i++)
11                     temp.add(i);
12                 res.add(temp);
13                 small = small+1;
14                 big = small+1;
15             }
16             else if(my_sum>sum) small++;
17             else big++;
18         }
19         return res;
20     }
21     private int sumlist(int small,int big){
22          return (big+small)*(big-small+1)/2;
23     }
24 }

 

posted @ 2018-01-03 13:24  乐乐章  阅读(143)  评论(0编辑  收藏  举报