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][]);
}
}
附加GitHub链接
来源:CSDN
作者:L_P_
链接:https://blog.csdn.net/qq_36008321/article/details/104704286