• 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测试程序源码

  • 相关阅读:
    ajax提交转码解码
    关于idea开发工具常用的快捷键
    oracle 查询某个时间段数据
    hibernate : object references an unsaved transient instance 问题
    log4j日志
    JS关键字 import
    代码正常,junit却报错原因及解决方法
    hdu 5868 Polya计数
    hdu 5893 (树链剖分+合并)
    hdu 5895 广义Fibonacci数列
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214823.html
Copyright © 2020-2023  润新知