题解 | #和为S的连续正数序列#
和为S的连续正数序列
https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe
import java.util.ArrayList; public class Solution { public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> result = new ArrayList<>(); for (int start = 1; start <= sum / 2; start++) { int tempSum = 0; ArrayList<Integer> integers = new ArrayList<>(); for (int j = start; j < sum; j++) { integers.add(j); tempSum += j; if (tempSum == sum) { result.add(integers); break; } else if (tempSum > sum) { break; } } } return result; } }
解题思想:穷举,双层循环,但是sum/2可以提前终止循环。超过sum/2之后的和肯定大于s。
#算法##算法笔记#