zoukankan      html  css  js  c++  java
  • leetcode111:combination-sum

    题目描述

    给出一组候选数C和一个目标数T,找出候选数中加起来和等于T的所有组合。
    C中的数字在组合中可以被无限次使用
    注意:
    • 题目中所有的数字(包括目标数T)都是正整数
    • 你给出的组合中的数字 (a 1, a 2, … , a k) 要按非递增排序 (ie, a 1 ≤ a 2 ≤ … ≤ a k).
    • 结解集中不能包含重复的组合
     
    例如:给定的候选数集是[2,3,6,7],目标数是7
    解集是:
    [7]
    [2, 2, 3]

    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 (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k).
    • The solution set must not contain duplicate combinations.


    For example, given candidate set2,3,6,7and target7, 
    A solution set is: 
    [7]
    [2, 2, 3]

    class Solution {
    public:
        vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
            vector <vector<int>>res;
            vector<int> temp;
            sort(candidates.begin(),candidates.end());
            Sum(res,temp,candidates,0,target);
            return res;
        }
        void Sum(vector <vector <int>> &res,vector<int> &temp,vector<int >&candidates,int k,int target){
            if (target==0){
                res.push_back(temp);
                return ;
            }
            if (target <0 || k>=candidates.size())
                return ;
            vector<int> t =temp;
            temp.push_back(candidates[k]);
            Sum(res,temp,candidates,k,target-candidates[k]);
            Sum(res,t,candidates,k+1,target);
            
        }
    };

  • 相关阅读:
    计蒜客 跳跃游戏2
    计蒜客 跳跃游戏
    2018 计蒜之道-初赛 第一场 A-百度无人车
    poj 3625 (最小生成树算法)
    poj 3623(贪心)
    poj2386(dfs搜索水题)
    poj 2761 主席树的应用(查询区间第k小值)
    POJ 2456 编程技巧之------二分查找思想的巧妙应用
    POJ 1995(有关快速幂运算的一道水题)
    1441:【例题2】生日蛋糕
  • 原文地址:https://www.cnblogs.com/hrnn/p/13415361.html
Copyright © 2011-2022 走看看