Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

README.md

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

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

 

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: 
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5
Output: 
[
[1,2,2],
[5]
]

 

Constraints:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

Companies: Amazon, Bloomberg, TikTok

Related Topics:
Array, Backtracking

Similar Questions:

Solution 1. Backtracking

// OJ: https://leetcode.com/problems/combination-sum-ii
// Author: github.com/lzl124631x
// Time: O(2^N)
// Space: O(N)
class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& A, int target) {
        sort(begin(A), end(A));
        vector<vector<int>> ans;
        vector<int> tmp;
        function<void(int, int)> dfs = [&](int i, int target) {
            if (target == 0) {
                ans.push_back(tmp);
                return;
            }
            if (i == A.size()) return;
            if (target >= A[i]) { // pick A[i]
                tmp.push_back(A[i]);
                dfs(i + 1, target - A[i]);
                tmp.pop_back();
            }
            // if we skip A[i], we need to skip all elements that are the same as A[i]
            while (i + 1 < A.size() && A[i + 1] == A[i]) ++i;
            dfs(i + 1, target);
        };
        dfs(0, target);
        return ans;
    }
};

Solution 2. Backtracking

// OJ: https://leetcode.com/problems/combination-sum-ii/
// Author: github.com/lzl124631x
// Time: O(2^N)
// Space: O(N)
class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& A, int target) {
        sort(begin(A), end(A));
        vector<vector<int>> ans;
        vector<int> tmp;
        function<void(int, int)> dfs = [&](int start, int target) {
            if (target == 0) {
                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(i + 1, target - A[i]);
                tmp.pop_back();
            }
        };
        dfs(0, target);
        return ans;
    }
};