zoukankan      html  css  js  c++  java
  • LeetCode(40) Combination Sum II

    题目

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

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

    Note:
    All numbers (including target) will be positive integers.
    Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
    The solution set must not contain duplicate combinations.
    For example, given candidate set 10,1,2,7,6,1,5 and target 8,
    A solution set is:
    [1, 7]
    [1, 2, 5]
    [2, 6]
    [1, 1, 6]

    分析

    与上一题39 Combination Sum本质相同,只不过需要注意两点:每个元素只能出现结果序列中一次,结果序列不可重复。

    只需利用find函数添加一个判重即可。

    AC代码

    class Solution {
    public:
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            if (candidates.empty())
                return vector<vector<int> >();
    
            sort(candidates.begin(), candidates.end());
    
            ret.clear();
    
            vector<int> tmp;
            combination(candidates, 0, tmp, target);
            return ret;
        }
    
        void combination(vector<int> &candidates, int idx, vector<int> &tmp, int target)
        {
            if (target == 0)
            {
                if (find(ret.begin(), ret.end(), tmp) == ret.end())
                    ret.push_back(tmp);
                return;
            }
            else{
                int size = candidates.size();
                for (int i = idx; i < size; ++i)
                {
                    if (target >= candidates[i])
                    {
                        tmp.push_back(candidates[i]);
                        combination(candidates, i + 1, tmp, target - candidates[i]);
                        tmp.pop_back();
                    }//if
                }//for
            }//else
        }
    
    private:
        vector<vector<int> > ret;
    };

    GitHub测试程序源码

  • 相关阅读:
    FCKeditor firefox Ajax提交,内容为空.解决.
    Javascript:Go to top of page
    js实现两级联动下拉列表
    php+mysql实现二级联动下拉列表
    ajax 实现两级级联下拉列表
    SharpDevelop_3.2.1.6466_Setup软件安装汉化
    c#拓展项目作业
    摇色子(两颗色子)
    C#编程实践51题目解答
    编程实践53
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214823.html
Copyright © 2011-2022 走看看