T39:和為S的連續正數序列(Java)
阿新 • • 發佈:2018-12-09
題目:輸出所有和為S的連續正數序列。序列內按照從小至大的順序,序列間按照開始數字從小到大的順序
比如 輸入15
輸出為
public class FindContinuousSequence1 { public static ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> listAll=new ArrayList<ArrayList<Integer> >(); if(sum<3){ return listAll; } int small=1; int big=2; int mid=(1+sum)/2; int curSum=3; while(small<mid){ while(curSum>sum&&small<mid){ curSum-=small; small++; } if(curSum==sum){ ArrayList<Integer> list=new ArrayList<Integer>(); add(list,small,big); listAll.add(list); } big++; curSum+=big; } return listAll; } private static void add(ArrayList<Integer> list, int small, int big) { for(int i=small;i<=big;i++){ list.add(i); } } public static void main(String[] args) { ArrayList<ArrayList<Integer>> listAll=FindContinuousSequence(15); for(ArrayList list:listAll){ System.out.println(list); } } }