leetcode [39] Combination Sum

本文介绍了一种使用回溯法解决组合求和问题的算法。给定一个无重复元素的数组和一个目标值,通过递归搜索所有可能的组合,使这些组合的元素之和等于目标值。文章提供了C++和Python两种语言的实现代码。
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]
 ]
题目大意:
给一个不重复的数组,寻找数组中数字的排列组合,使得这个排列组合之和等于target。数组中的数字可以重复使用,找到数组中全部的排列组合。
 
解法:
我首先想到的是回溯法,首先对数组中的数进行排序,tmp数组记录当前排列组合,tmpSum记录当前排列组合之和,index记录遍历到数组哪一个数了。
C++:
class Solution {
private:
    void combinationCore(vector<int>&candidates,int index,int tmpSum,int target,vector<int>&tmp,vector<vector<int>>&res){
        if(tmpSum>target) return;
        if(tmpSum==target) {
            res.push_back(tmp);
            return;
        }
        for(int i=index;i<candidates.size();i++){
            tmpSum+=candidates[i];
            tmp.push_back(candidates[i]);
            combinationCore(candidates,i,tmpSum,target,tmp,res);
            tmpSum-=candidates[i];
            tmp.pop_back();
        }
    }

public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>>res;
        vector<int>tmp;
        sort(candidates.begin(),candidates.end());
        combinationCore(candidates,0,0,target,tmp,res);

        return res;
    }
};
  其实自己写的代码有点冗余,其中的tmpSum可以不需要,直接使用target减去值,再和零进行比较,递归调用的时候也是。可以参考下面的python代码。
 
Python:
class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res=[]
        candidates.sort()
        self.dfs(candidates,target,0,[],res)
        return res

    def dfs(self,candidates,target,index,path,res):
        if target<0:
            return
        if target==0:
            res.append(path)
            return
        for i in range(index,len(candidates)):
            self.dfs(candidates,target-candidates[i],i,path+[candidates[i]],res)

 写上面的代码发现python中的list进行合并可以采用[]+[]

 range(start,end)返回的列表并不包括end

转载于:https://www.cnblogs.com/xiaobaituyun/p/10595046.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值