[LeetCode] Combination Sum

39. Combination Sum

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

  • new solution update 2022.02.07
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    class Solution {
    public:
    vector<vector<int>> combinationSum(vector<int>& c, int target) {
    sort(c.begin(), c.end());
    vector<vector<int>> res;
    vector<int> tmp;
    dfs(res,tmp,c,target,0);
    return res;
    }

    void dfs(vector<vector<int>>& res, vector<int>& tmp, vector<int>& c, int t, int i) {
    if(!t) {
    res.push_back(tmp);
    return;
    }
    for(; i < c.size() and c[i] <= t; i++) {
    tmp.push_back(c[i]);
    dfs(res, tmp, c, t - c[i], i);
    tmp.pop_back();
    }
    }
    };
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& c, int t) {
unordered_map<int, vector<vector<int>>> dp;
sort(begin(c), end(c));
c.erase(upper_bound(begin(c), end(c), t), end(c));
for(auto& n : c) {
dp[n].push_back(vector<int>{n});
for(int i = 1; i <= t - n; i++) {
if(!dp.count(i)) continue;
for(auto& vec : dp[i]) {
vector<int> tmp(begin(vec), end(vec));
tmp.push_back(n);
dp[i + n].push_back(tmp);
}
}
}
return dp[t];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/16/PS/LeetCode/combination-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.