输出所有和为S的连续正数序列, 序列内按照从小到大的顺序.
public class DemoA {
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
int low = 1;
int high = 2; // 两个起点,相当于动态窗口的两边,根据其窗口内的值的和来确定窗口的位置和大小
while (low < high) {
int total = (low + high) * (high - low + 1) / 2;
// 由于是连续的,差为1的一个序列,那么求和公式是(a0+an)*n/2
if (total == sum) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = low; i <= high; i++) {
list.add(i);
}
result.add(list);
low++;
} else if (total < sum) {
high++;
} else {
low++;
}
}
return result;
}
}