题目描述:输出所有和为 S 的连续正数序列。例如和为 100 的连续序列有:[9, 10, 11, 12, 13, 14, 15, 16],[18, 19, 20, 21, 22]。
题解:
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
int small = 1, big = 2;
int cur = 3;
while(small < (sum+1)/2){
if(cur == sum){
ArrayList<Integer> list = new ArrayList<>();
for(int i = small; i<=big; i++)
list.add(i);
ret.add(list);
cur-=small;
big++;
small++;
cur+=big;
} else if(cur <sum){
big++;
cur+=big;
}else{
cur-=small;
small++;
}
}
return ret;
}
}