2019-11-02 12:07:41 +08:00
|
|
|
# 57.2 和为 S 的连续正数序列
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
2020-11-04 02:26:10 +08:00
|
|
|
[牛客网](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)
|
|
|
|
|
|
|
|
## 题目描述
|
2019-11-02 12:07:41 +08:00
|
|
|
|
2020-11-04 02:26:10 +08:00
|
|
|
输出所有和为 S 的连续正数序列。例如和为 100 的连续序列有:
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
```
|
|
|
|
[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;
|
|
|
|
}
|
|
|
|
```
|