216. Combination Sum III
保证subset.size( ) == k && target == 0的时候结束DFS
subset.size( ) > k || target < 0返回。
class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> res = new ArrayList<>(); if(k <= 0 || n < 1) return res; dfs(res, new ArrayList<Integer>(), k, n, 1); return res; } private void dfs(List<List<Integer>> res, List<Integer> subset, int k, int target, int index){ if(subset.size() > k && target < 0) return; if(subset.size() == k && target == 0){ res.add(new ArrayList<Integer>(subset)); return; } for(int i = index; i <= 9; i++){ subset.add(i); dfs(res, subset, k, target - i, i + 1); subset.remove(subset.size() - 1); } } }
377. Combination Sum IV
DFS: 此方法超时
class Solution { int count; public int combinationSum4(int[] nums, int target) { if(nums == null || nums.length == 0) return 0; dfs(nums, target, new ArrayList<Integer>()); return count; } private void dfs(int[] nums, int target, List<Integer> subset){ if(target == 0){ count++; return; } if(target < 0){ return; } for(int i = 0; i < nums.length; i++){ subset.add(nums[i]); dfs(nums, target - nums[i], subset); subset.remove(subset.size() - 1); } } }
DP: i - nums[ j ]表 当前nums[ j ]与之前comb[ ] 中的组合数字继续组合得到target。
class Solution { public int combinationSum4(int[] nums, int target) { int[] comb = new int[target + 1]; comb[0] = 1; for(int i = 1; i < comb.length; i++){ for(int j = 0; j < nums.length; j++){ if(i - nums[j] >= 0){ comb[i] += comb[i - nums[j]]; } } } return comb[target]; } }