天天看點

輸出所有和為S的連續正數序列。序列内按照從小至大的順序,序列間按照開始數字從小到大的順序

import java.util.ArrayList;

public class Solution {

    public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum){

        ArrayList<ArrayList<Integer> > list=new ArrayList<ArrayList<Integer> >();

        if(sum < 3){

            return list;

        }

        int first=1;//設定第一個數字

        int second=2;//設定最後一個數字

        while(first < (sum+1) /2){

            ArrayList<Integer> list_sequence = new ArrayList<Integer>();

            int count=0;

            for(int i=first;i<=second;i++){

                count+=i;

            }

            if(count == sum){

              //序列滿足條件

              for(int i=first;i<=second;i++){

                list_sequence.add(i);

             } 

                first++;

            }else if(count > sum){

                first++;

            }else{

                second++;

            }

            if(list_sequence.size() > 0){

                list.add(list_sequence);

            }

        }

        return list;

    }

}

繼續閱讀