剑指offer(41)和为s的连续正数序列
import java.util.ArrayList;
import java.util.Scanner;
//和为s的连续正数序列
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
if(sum < 3){
return list;
}
int small = 1, big = 2, curSum = small + big, middle = (1 + sum) / 2;
while(small < middle){
if(curSum == sum){
list.add(addList(small, big));
}
while(curSum > sum && small < middle){
curSum -= small;//如果现在和比sum要大,则把和中减一个small,再把small减小
small++;
if(curSum == sum){
list.add(addList(small, big));
}
}
big++;
curSum += big;//这两句的顺序不能变,如果现在得到的和比所求要小,则要加进来的数字应该是已经加一的数字,所以先加加
}
return list;
}
public ArrayList<Integer> addList(int small, int big){
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = small; i <= big; i++){
list.add(i);
}
return list;
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
sc.close();
NoFourtyone fourtyone = new NoFourtyone();
ArrayList<ArrayList<Integer>> res = fourtyone.FindContainsSequence(s);
for(int i = 0;i < res.size();i++){
System.out.println(res.get(i));
}
}
}