题解 | #和为S的连续正数序列#
和为S的连续正数序列
http://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe
import java.util.ArrayList;
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int n) {
if (n <= 1) return res;
//用滑动窗口
int l = 0;
int r = 0;
int sum = 0;
while (r < n){
while (sum >= n){
l++;
sum -= l;
if (sum == n){
add(l, r);
}
}
while (sum < n){
r++;
sum += r;
if (sum == n){
add(l, r);
}
}
}
return res;
}
private void add(int l, int r){
ArrayList<Integer> tmp = new ArrayList<>();
for (int i = l + 1; i <= r; i++){
tmp.add(i);
}
res.add(tmp);
}
}