[LC] 40. Combination Sum II
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
[10,1,2,7,6,1,5]
8
Example 2:
Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,2,2], [5] ]
Time: O(2^N)
Space: O(N)
class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> res = new ArrayList<>(); if (candidates == null || candidates.length == 0) { return res; } Arrays.sort(candidates); List<Integer> lst = new ArrayList<>(); helper(res, lst, candidates, target, 0); return res; } private void helper(List<List<Integer>> res, List<Integer> lst, int[] candidates, int reminder, int index) { if (reminder < 0) { return; } if (reminder == 0) { res.add(new ArrayList<>(lst)); } for (int i = index; i < candidates.length; i++) {
//i > index will only skip when numbers before cur is used.
// i > 0 skip all one combination like [1, 1, 6]
if(i > index && candidates[i] == candidates[i - 1]) { continue; } lst.add(candidates[i]); helper(res, lst, candidates, reminder - candidates[i], i + 1); lst.remove(lst.size() - 1); } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步