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.”
  • 相关阅读:
    AtCoder 杂题乱写
    JOISC2020 遗迹
    【考试总结】20220107
    AGC021F Trinity
    CCPC2021 广州A/CF Gym103415A
    【考试总结】20220115
    JDK8 时间api当天的开始和截至时间
    技术方案模板
    正则表达式
    组合算法
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4581931.html
Copyright © 2011-2022 走看看