zoukankan      html  css  js  c++  java
  • [LeetCode] #38 Combination Sum

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

    The same repeated number may be chosen from C unlimited number of times.

    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 2,3,6,7 and target 7
    A solution set is: 
    [7] 
    [2, 2, 3] 

    本题利用回溯算法求解,重点在于消除重复。时间:12ms。代码如下:

    class Solution {
    public:
        void makeCombination(vector<vector<int> > &ans, vector<int> &candidates, vector<int> &tmp, int target, int cur){
            for (int i = cur; i < candidates.size(); ++i){
                if (0 == target) {
                    ans.push_back(tmp);
                    return;
                }
                if (candidates[i] <= target){
                    tmp.push_back(candidates[i]);
                    makeCombination(ans, candidates, tmp, target - candidates[i], i);
                    tmp.pop_back();
                }
                if (candidates[i] > target){
                    return;
                }
            }
        }
        vector<vector<int>> combinationSum(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;
            makeCombination(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.”
  • 相关阅读:
    网络协议分析-ICMP协议分析
    网络协议分析-IP协议分析
    网络协议分析-ARP协议分析
    网络协议分析-Ethernet
    Centos7 _dns服务器搭建及配置
    centos7_vsftpd-ssl/tls搭建及ftp加固
    HTTP请求的六种方式
    Winserver03-Web SSL服务搭建
    webstorage和cookie的区别
    sessionstorage和localstorage的区别
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4581931.html
Copyright © 2011-2022 走看看