Combination Sum

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:

[
  [7],
  [2,2,3]
]

Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:

[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

给定一组候选数字(candidates)(没有重复)和目标数字(target),找到候选人数总和目标的候选人中的所有独特组合。

可以从候选者无限次数中选择相同的重复数字。

2,题目思路

对于这道题,是给定一系列的候选数字,然后再给出一个数字目标,找出所有从候选数字内选出的数字之和等于目标的结果集合。

在求解时, 我们使用回溯的办法来求解这道题。

看到算法的实现和之前Permutations的实现非常类似,于是想到回溯递归的区别到底是什么。

之后在查找出资料后,专门写一篇博客探讨这个问题。

3,代码实现

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> res;
        vector<int> tmpRes;
        backTracking(candidates, target, res, tmpRes, 0);
        return res;
    }
private:
    void backTracking(vector<int> &candidates, int target, vector<vector<int>> &res, vector<int> &tmpRes, int begin){
        //tmpRes满足给定的target条件
        if(target == 0){
            res.push_back(tmpRes);
            return;
        }
        
        //target>=candidates[i]是一种减枝的功能
        for(int i = begin;i<candidates.size() && target>=candidates[i];i++){
            tmpRes.push_back(candidates[i]);;
            backTracking(candidates, target-candidates[i], res, tmpRes, i);
            tmpRes.pop_back();  //恢复
        }
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值