Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C 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. For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]

public class Solution { public List> combinationSum2(int[] candidates, int target) { List> result = new ArrayList<>(); Arrays.sort(candidates); dfs(result, new ArrayList(), candidates, target, 0); return result; } private void dfs(List> res, ArrayList path, int[] cand, int target, int cur) { if(target == 0) { res.add(new ArrayList(path)); return; } else if (target > 0) { for(int i = cur; i < cand.length; i++) { if(i > cur && cand[i] == cand[i - 1]) continue; path.add(cand[i]); dfs(res, path, cand, target - cand[i], i + 1); path.remove(path.size() - 1); } } } }

results matching ""

    No results matching ""