連結:
https://leetcode.com/problems/combination-sum-iii/
大意:
給定一個數k和一個數n,要求從1-9中找出k個不同的數,其和為n。求出所有這樣的組合。注意:每個數字在一個組合内隻能被使用一次。例子:

思路:
經典的回溯。具體思路看代碼。
代碼:
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<>();
// k個0-9的數最小的和為(1 + k) * k / 2 最大的和為 (19 - k) * k / 2
int minSum = (1 + k) * k / 2, maxSum = (19 - k) * k / 2;
if (n < minSum || n > maxSum)
return res;
dfs(k, n, 1, res, new ArrayList<>());
return res;
}
public void dfs(int k, int n, int idx, List<List<Integer>> res, List<Integer> list) {
// 當收集到k個數時無論這k個數的和是否等于n 都會return
if (k == list.size()) {
if (n == 0) {
res.add(new ArrayList<>(list));
}
return ;
}
while (idx <= 9) {
// 剪枝
if (n - idx < 0)
break;
list.add(idx);
dfs(k, n - idx, idx + 1, res, list);
list.remove(list.size() - 1); // 回溯
idx++;
}
}
}
結果:
結論:
經典回溯題,掌握回溯的模闆就ok