51 lines
1.2 KiB
Java
51 lines
1.2 KiB
Java
# 57.2 和为 S 的连续正数序列
|
||
|
||
[NowCoder](https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe?tpId=13&tqId=11194&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
||
|
||
## 题目描述
|
||
|
||
输出所有和为 S 的连续正数序列。
|
||
|
||
例如和为 100 的连续序列有:
|
||
|
||
```
|
||
[9, 10, 11, 12, 13, 14, 15, 16]
|
||
[18, 19, 20, 21, 22]。
|
||
```
|
||
|
||
## 解题思路
|
||
|
||
```java
|
||
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
|
||
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
|
||
int start = 1, end = 2;
|
||
int curSum = 3;
|
||
while (end < sum) {
|
||
if (curSum > sum) {
|
||
curSum -= start;
|
||
start++;
|
||
} else if (curSum < sum) {
|
||
end++;
|
||
curSum += end;
|
||
} else {
|
||
ArrayList<Integer> list = new ArrayList<>();
|
||
for (int i = start; i <= end; i++)
|
||
list.add(i);
|
||
ret.add(list);
|
||
curSum -= start;
|
||
start++;
|
||
end++;
|
||
curSum += end;
|
||
}
|
||
}
|
||
return ret;
|
||
}
|
||
```
|
||
|
||
|
||
|
||
|
||
|
||
|
||
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-1.png"></img></div>
|