Leetcode 216.组合总和III
题目要求
- 找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:
- 返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
示例 1:
输入: k = 3, n = 7
输出: [[1,2,4]]
解释:
1 + 2 + 4 = 7
没有其他符合的组合了。
示例 2:
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
解释:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
没有其他符合的组合了。
示例 3:
输入: k = 4, n = 1
输出: []
解释: 不存在有效的组合。
在[1,9]范围内使用4个不同的数字,我们可以得到的最小和是1+2+3+4 = 10,因为10 > 1,没有有效的组合。
回溯法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); int sum = 0; public List<List<Integer>> combinationSum3(int k, int n) { backtracking(k, n, 1); return res; }
public void backtracking(int k, int n, int startIndex) { if (sum == n && path.size() == k) { res.add(new ArrayList<>(path)); return; }
for (int i = startIndex; i < 10; i++) { sum += i; path.add(i); backtracking(k, n, i + 1); sum -= i; path.remove(path.size() - 1); } } }
|
剪枝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); int sum = 0; public List<List<Integer>> combinationSum3(int k, int n) { backtracking(k, n, 1); return res; }
public void backtracking(int k, int n, int startIndex) { if (sum > n) return;
if (path.size() > k) return;
if (sum == n && path.size() == k) { res.add(new ArrayList<>(path)); return; }
for (int i = startIndex; i < 10; i++) { sum += i; path.add(i); backtracking(k, n, i + 1); sum -= i; path.remove(path.size() - 1); } } }
|