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.”
  • 相关阅读:
    vue学习笔记 样式 class style(五)
    vue学习笔记 计算属性(四)
    vue学习笔记 模板语法(三)
    vue学习笔记 实例(二)
    vue学习笔记 概述(一)
    Babel指南——基本环境搭建
    手动es6编译es5(命令行)
    TrimPath
    git 远程仓库管理
    CSS左侧固定宽 右侧自适应(兼容所有浏览器)
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4581931.html
Copyright © 2011-2022 走看看