297. 和爲s的連續正數序列
問題描述:
輸入一個正整數 target ,輸出所有和爲 target 的連續正整數序列(至少含有兩個數)。
序列內的數字由小到大排列,不同序列按照首個數字從小到大排列。
示例1
輸入:target = 9
輸出:[[2,3,4],[4,5]]
示例1
輸入:target = 15
輸出:[[1,2,3,4,5],[4,5,6],[7,8]]
完整代碼:
// Encodes a tree to a single string.
class Solution {
public int[][] findContinuousSequence(int target) {
if (target < 3)
return null;
int small = 1 , big = 2;
int curr = small + big;
List<int[]> res = new ArrayList<>();
int middle = (target+1)>>>1;
while (small < middle) {
if (curr == target){
int tmp[] = new int[big - small + 1];
for (int i = small,j = 0;i <= big; i++,j++) {
tmp[j] = i;
}
res.add(tmp);
}
while (curr > target && small < middle) {
curr -= small;
small++;
if (curr == target){
int tmp[] = new int[big - small + 1];
for (int i = small,j = 0;i <= big; i++,j++) {
tmp[j] = i;
}
res.add(tmp);
}
}
big++;
curr+=big;
}
return res.toArray(new int[0][]);
}
}