zoukankan      html  css  js  c++  java
  • 39. Combination Sum (Back-Track)

    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] 

    思路:每个元素有被选和不选两种情况=>带回溯的递归

    class Solution {
    public:
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            sort(candidates.begin(), candidates.end());
            backTracking(candidates,0,target);
            return result;
        }
        
        void backTracking(vector<int>& candidates, int depth, int target){
            if(target==0){
                result.push_back(item);
                return;
            }
            if(target<0 || depth >= candidates.size()) return;
            
            item.push_back(candidates[depth] );
            backTracking(candidates,depth, target-candidates[depth]);
            item.pop_back();
            backTracking(candidates,depth+1, target);
        }
    private:
        vector<int> item;
        vector<vector<int>> result;
    };
  • 相关阅读:
    做数据库维修工、还是码农,讨论走下神坛的职业【摘自vage】
    4.4 Web存储
    4.3 createjs
    4.2 HTML Canvas标签
    4.2 拖放
    4.1 HTML5 音频
    3.2 JacaScript面向对象
    3.1 JavaScript基础
    2.7 CSS动画
    2.6 CSS基本操作
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4855325.html
Copyright © 2011-2022 走看看