topic
Address: 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 backtracking solution
Analytical thinking:
- Solution that backtracking recursive, recursive have outlet conditions
if (sum == 0 && k == 0)
, when the condition put into the result set list. - Backtracking like life choices, or choose to do this thing
list.add(i);
, or choose not to this matterlist.remove(list.size() - 1);
. - Just remember to act otherwise is empty, perform a recursive
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);
}
}
}