看代码:
class Solution { List<List<Integer>> res = new LinkedList<>(); public List<List<Integer>> combinationSum(int[] candidates, int target) { LinkedList<Integer> list = new LinkedList<>(); dfs(candidates, target, 0, res, list); return res; } private void dfs(int[] candidates, int target, int idx, List<List<Integer>> res, LinkedList<Integer> list) { if (target == 0) { res.add(new ArrayList<>(list)); return; } if (idx == candidates.length) { return; } // 跳过当前数字 dfs(candidates, target, idx + 1, res, list); // 选择当前数 if (target - candidates[idx] >= 0) { list.add(candidates[idx]); dfs(candidates, target - candidates[idx], idx, res, list); list.removeLast(); } } }
LeetCode40题:
**注意:**结果集不重复,数字不可重复使用,数组中有重复数字