题目
地址:https://leetcode.com/problems/combination-sum-iii/
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Note:
All numbers will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: k = 3, n = 7
Output: [[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
DFS回溯解法
思路解析:
- 回溯的解法在于递归,递归要有出口条件
if (sum == 0 && k == 0)
, 当满足条件则把集合添加到结果列表中。 - 回溯的就像人生选择,要么选择做这件事情
list.add(i);
, 要么选择不做这件事情list.remove(list.size() - 1);
。 - 记得要有行动,否则就是空谈,执行递归
dfs(resultList, list, k - 1, sum - i, i + 1);
package backtracking;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// https://leetcode.com/problems/combination-sum-iii/
public class CombinationSumIII {
public static void main(String[] args) {
int k = 3;
int n = 9;
CombinationSumIII obj = new CombinationSumIII();
List<List<Integer>> resultList = obj.combinationSum3(k ,n);
System.out.println(Arrays.toString(resultList.toArray()));
}
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
// dfs
dfs(resultList, new ArrayList<Integer>(), k, n, 1);
return resultList;
}
private void dfs(List<List<Integer>> resultList, List<Integer> list, int k, int sum, int start) {
if (sum == 0 && k == 0) {
resultList.add(new ArrayList<Integer>(list));
return;
}
if (sum < 0) {
return;
}
for (int i = start; i <= 9; i++) {
// add num
list.add(i);
dfs(resultList, list, k - 1, sum - i, i + 1);
// not add num
list.remove(list.size() - 1);
}
}
}