LeetCode--Combination Sum

本文介绍了一种使用深度优先搜索解决组合求和问题的方法。针对给定候选数集和目标数,寻找所有可能的组合使得候选数之和等于目标数。文章通过示例详细解释了算法实现过程及注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]

这道题看过好几次最开始都没看出怎么做就一直留着,结果今天在做Subsets 这道题时找到了灵感,使用深度优先的方法搜索,并且用一个vector记录向量,找到合适的向量时即将它保存在结果中,并进行回溯操作。这道题相比于Subsets中使用回溯法而言更麻烦一些。以后需要注意这种解题方法,当要求解的结果是一系列向量的集合时使用dfs搜索记录路径这种方法。对于输入candidates=[1,2] ,target=3,遍历的方向如图: 
这里写图片描述

runtime:28ms

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> result;
        vector<int> path;
        sort(candidates.begin(),candidates.end());
        helper(candidates,0,0,target,path,result);
        return result;
    }

void helper(vector<int> &nums,int pos,int base,int target,vector<int>& path,vector<vector<int>> & result)
    {
        if(base==target)
        {
            result.push_back(path);
            return ;
        }
        if(base>target)
            return ;
        for(int i=pos;i<nums.size();i++)
        {
            path.push_back(nums[i]);
            helper(nums,i,base+nums[i],target,path,result);
            path.pop_back();
        }
    }
};
转自: http://blog.youkuaiyun.com/u012501459/article/details/46779021


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值