My recursive solution, easy to understand

  • 3

    First, sort the candidates and remove duplicates, I did this with set using 2 line

    Second, call the depth-first-search function to generate the result. In the function, I marked the largest element has been used, and only attempt to use the same or larger element when doing recursive calls which makes the result meet the ordering restriction.

    my code:

    class Solution {
        void dfs(vector<int> &can, int t, vector<int> &cur, int k, vector<vector<int> > &res) {
            if(t == 0) {
            if(can[k] <= t) {
                for(int i = k; i < can.size() and can[i] <= t; i++) {
                    dfs(can, t - can[i], cur, i, res);
        vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
            vector<vector<int> > res;
            if(candidates.size() == 0) return res;
            set<int> dedup(candidates.begin(), candidates.end());
            candidates = vector<int>(dedup.begin(), dedup.end());
            vector<int> tmp;
            dfs(candidates, target, tmp, 0, res);
            return res;

  • 0
    This post is deleted!

  • 0

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example

  • 0

    inorder to delete duplicates, you can use sort , unique and resize method of vector

  • 0

    not a good idea, using set is faster

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.