LeetCode CombinationSum

class Solution {

public:

    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {

        

        sort(candidates.begin(), candidates.end());

        candidates.erase(unique(candidates.begin(), candidates.end()), candidates.end());

        

        vector<vector<int> > tmp;

        vector<int> sel;

        

        dfs(candidates, 0, target, sel, tmp);

        return tmp;

    }

    

    void dfs(vector<int>& nums, int pos, int tar, vector<int>& sel, vector<vector<int> >& res) {

        if (tar == 0) {

            res.push_back(sel);

            return;

        }

        if (pos >= nums.size()) return;

        int cur = nums[pos];

        int add = 0;

        for (add = 0; add <= tar; add+=cur) {

            if (add != 0) {

                sel.push_back(cur);

            }

            dfs(nums, pos + 1, tar - add, sel, res);

        }

        for (int i = add/cur - 1; i>0; i--) {

            sel.pop_back();

        }

    }

};

dfs搜索,通过unique操作去除重复的候选数字,避免产生重复的序列

你可能感兴趣的:(LeetCode)