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] 

    本题与上题类似,不过首先需要对数组进行排序,然后需要去除重复。时间:8ms。代码如下:

    class Solution {
    public:
        void makeCombination2(vector<vector<int>>& ret, vector<int>& candidates, vector<int>& v, int target, int cur){
            if (target == 0){
                ret.push_back(v);
                return;
            }
            int rep = -1;
            for (size_t i = cur; i < candidates.size(); ++i){
                if (rep == candidates[i])
                    continue;
                if (target >= candidates[i]){
                    rep = candidates[i];
                    v.push_back(candidates[i]);
                    makeCombination2(ret, candidates, v, target - candidates[i], i + 1);
                    v.pop_back();
                }
                else
                    return;
            }
        }
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            vector<vector<int>> ret;
            sort(candidates.begin(), candidates.end());
            if (candidates.empty() || target < candidates[0])
                return ret;
            vector<int> v;
            makeCombination2(ret, candidates, v, target, 0);
            return ret;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    多轨车皮编序问题
    [Luogu1032] 字串变换
    [POJ1101] The Game
    Linux 下源码编译FFMEG
    交叉编译 tcpdump
    现代电视原理-电视传像原理
    Dos:‘锘緻echo’ 不是内部或外部命令,也不是可运行的程序或批处理文件
    Win7 登入壁纸修改
    Office 2016安装后的优化设置
    Linux 系统目录结构
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4581941.html
Copyright © 2011-2022 走看看