zoukankan      html  css  js  c++  java
  • 【LeetCode练习题】Combination Sum

    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 (a1a2, … , 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]

    从给定集合里找出和为Target的数的组合,一个数可以重复使用。

    结果集不能重复,且每一个结果内按升序排列。

    解题思路:

    这是一个很好的题目,用到了回溯法,考点跟之前那道Permutation有点点像。代码有相似之处。

    每次遇到下一个数时,如果它比target大,因为nums是排序的,那么肯定匹配不上了,返回。

    否则的话,将这个数push_back到中间结果里,开始递归。递归结束时需要将这个数pop出来,在这个位置继续尝试下一个数。

    代码如下:

    class Solution {
    public:
        vector<vector<int> > combinationSum(vector<int> &nums, int target) {
            sort(nums.begin(),nums.end());
            vector<int> temp;  //中间结果
            vector<vector<int>> result; //最终结果
            dp(nums,0,target,temp,result);
            return result;
        }
        
        void dp(vector<int> &nums,int start,int target,vector<int> &temp,vector<vector<int>> &result){
            if(target == 0){   //找到了一个合法的解
                result.push_back(temp);
                return ;
            }
            
            for(int i = start; i < nums.size(); i++){  
                if(nums[i] > target){  //剪枝
                    return ;
                }
                temp.push_back(nums[i]);  //往中间向量里加一个数
                dp(nums,i,target - nums[i],temp,result);
                temp.pop_back();  //撤销
            }
        }
    };
  • 相关阅读:
    执行上下文和作用域,作用域链
    学习笔记一:定位
    exports和module.exports的区别——学习笔记
    伪类和伪元素
    visibility和display
    CSS选择器,层叠
    Servlet乱码处理-------续集
    Servlet的乱码处理手记
    前端框架之Semantic UI
    最完整的Oracle11g 概述
  • 原文地址:https://www.cnblogs.com/4everlove/p/3662780.html
Copyright © 2011-2022 走看看