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.”
  • 相关阅读:
    PAT (Basic Level) Practise 1013 数素数
    PAT (Basic Level) Practise 1014 福尔摩斯的约会
    codeforces 814B.An express train to reveries 解题报告
    KMP算法
    rsync工具
    codeforces 777C.Alyona and Spreadsheet 解题报告
    codeforces 798C.Mike and gcd problem 解题报告
    nginx + tomcat多实例
    MongoDB副本集
    指针的艺术(转载)
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4581931.html
Copyright © 2011-2022 走看看