美文网首页
40. Combination Sum II/组合总和 II

40. Combination Sum II/组合总和 II

作者: 蜜糖_7474 | 来源:发表于2019-05-18 15:16 被阅读0次

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

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

    Note:

    All numbers (including target) will be positive integers.
    The solution set must not contain duplicate combinations.

    Example 1:

    Input: candidates = [10,1,2,7,6,1,5], target = 8,
    A solution set is:
    [
    [1, 7],
    [1, 2, 5],
    [2, 6],
    [1, 1, 6]
    ]

    Example 2:

    Input: candidates = [2,5,2,1,2], target = 5,
    A solution set is:
    [
    [1,2,2],
    [5]
    ]

    AC代码

    void digui(vector<int>& candidates, int target, int idx, int sum,
               vector<int>& v, set<vector<int>>& ans) {
        if (sum == target) {
            ans.insert(v);
            return;
        }
        else if (target < sum) return;
        else {
            for (int i = idx + 1; i < candidates.size(); ++i) {
                v.push_back(candidates[i]);
                digui(candidates, target, i, sum + candidates[i], v, ans);
                v.pop_back();
            }
        }
    }
    
    class Solution {
    public:
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            sort(candidates.begin(), candidates.end());
            set<vector<int>> ans;
            vector<vector<int>> ret;
            vector<int> v;
            digui(candidates, target, -1, 0, v, ans);
            for (auto t : ans) ret.push_back(t);
            return ret;
        }
    };
    

    优化AC代码(运行时去重)

    void digui(vector<int>& candidates, int target, int idx, int sum,
               vector<int>& v, vector<vector<int>>& ans) {
        if (sum == target) {
            ans.push_back(v);
            return;
        }
        else if (target < sum) return;
        else {
            for (int i = idx; i < candidates.size(); ++i) {
                if (i != idx && candidates[i] == candidates[i - 1]) continue;
                v.push_back(candidates[i]);
                digui(candidates, target, i + 1, sum + candidates[i], v, ans);
                v.pop_back();
            }
        }
    }
    
    class Solution {
    public:
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            sort(candidates.begin(), candidates.end());
            vector<vector<int>> ans;
            vector<int> v;
            digui(candidates, target, 0, 0, v, ans);
            return ans;
        }
    };
    

    总结

    1、自己写没有考虑去重,上网搜索学习了去重代码,快了整整三倍时间。
    2、递归中的for循环,无论是哪一层递归,只要是进入到第二次循环,那么意味着上一个数字已处理完毕,这个时候如果当前数字与上一个数字相同,那么必然会得到相同的结果,有点难理解,想了很久才绕出来,递归的思想还是不熟。

    相关文章

      网友评论

          本文标题:40. Combination Sum II/组合总和 II

          本文链接:https://www.haomeiwen.com/subject/kkdtzqtx.html