Question
Formatted question description: https://leetcode.ca/all/40.html
40. 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.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
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]
Algorithm
Based on Combination_Sum_I, add sorting to move duplicated numbers together and skip.
Code
Java
-
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Combination_Sum_II { class Solution { List<List<Integer>> result = new ArrayList<>(); public List<List<Integer>> combinationSum2(int[] candidates, int target) { if (candidates == null || candidates.length == 0) { return result; } // nlogn Arrays.sort(candidates); dfs(candidates, target, 0, new ArrayList<Integer>()); return result; } private void dfs(int[] candidates, int target, int start, ArrayList<Integer> onePath) { if (target < 0) { // target<0, assumption is all positive return; } if (target == 0) { result.add(new ArrayList<>(onePath)); // continue, and possible 1,-1 are next ones } for (int i = start; i < candidates.length; i++) { if (i > start && candidates[i] == candidates[i - 1]) continue; onePath.add(candidates[i]); dfs(candidates, target - candidates[i], i+1, onePath); // i+1, to use only once onePath.remove(onePath.size() - 1); } } } // https://leetcode.com/problems/combination-sum-ii/solution/ // official solution got "Time Limit Exceeded" error, funny but still a good idea solving this problem class Solution_lc { public List<List<Integer>> combinationSum2(int[] candidates, int target) { // container to hold the final combinations List<List<Integer>> results = new ArrayList<>(); LinkedList<Integer> comb = new LinkedList<>(); HashMap<Integer, Integer> counter = new HashMap<>(); for (int candidate : candidates) { if (counter.containsKey(candidate)) counter.put(candidate, counter.get(candidate) + 1); else counter.put(candidate, 1); } // convert the counter table to a list of (num, count) tuples List<int[]> counterList = new ArrayList<>(); counter.forEach((key, value) -> { counterList.add(new int[]{key, value}); }); backtrack(comb, target, 0, counterList, results); return results; } private void backtrack(LinkedList<Integer> comb, int remain, int curr, List<int[]> counter, List<List<Integer>> results) { if (remain == 0) { // make a deep copy of the current combination. results.add(new ArrayList<Integer>(comb)); return; } for (int nextCurr = curr; nextCurr < counter.size(); ++nextCurr) { int[] entry = counter.get(nextCurr); Integer candidate = entry[0], freq = entry[1]; if (freq <= 0) continue; // add a new element to the current combination comb.addLast(candidate); counter.set(nextCurr, new int[]{candidate, freq - 1}); // continue the exploration with the updated combination backtrack(comb, remain - candidate, nextCurr, counter, results); // backtrack the changes, so that we can try another candidate counter.set(nextCurr, new int[]{candidate, freq}); comb.removeLast(); } } } }
-
// OJ: https://leetcode.com/problems/combination-sum-ii/ // Time: O(N^2) // Space: O(N) class Solution { vector<vector<int>> ans; void dfs(vector<int> &A, int target, int start, vector<int> &tmp) { if (!target) { ans.push_back(tmp); return; } for (int i = start; i < A.size() && target >= A[i]; ++i) { if (i != start && A[i] == A[i - 1]) continue; tmp.push_back(A[i]); dfs(A, target - A[i], i + 1, tmp); tmp.pop_back(); } } public: vector<vector<int>> combinationSum2(vector<int>& A, int target) { sort(A.begin(), A.end()); vector<int> tmp; dfs(A, target, 0, tmp); return ans; } };
-
class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ def dfs(nums, target, start, visited, path, res): if target == 0: res.append(path + []) return for i in range(start, len(nums)): if i > start and nums[i] == nums[i - 1]: continue if target - nums[i] < 0: return 0 if i not in visited: visited.add(i) path.append(nums[i]) dfs(nums, target - nums[i], i + 1, visited, path, res) path.pop() visited.discard(i) candidates.sort() res = [] visited = set([]) dfs(candidates, target, 0, visited, [], res) return res