Leetcode 39. Combination Sum (递归)

39. Combination Sum

 Given a set of candidate numbers (C) (without duplicates) 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.
  • 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]
]

题目链接:https://leetcode.com/problems/combination-sum/description/
题目大意:给定一个数组和一个目标数字。求数组中和为目标数字的所有数字组合,数字可以重复相加。
解题思路:dfs递归,到最底层若满足条件就把数字组合加入答案集合。
代码如下:
class Solution {
public:
    vector<vector<int> > ans;
    vector<int> ca;
    int n;
    void dfs(int st,vector<int> a,int cur,int target){  
        if(cur == target){
            ans.push_back(a);  //a是每个可能的答案,如果最终满足条件,即a中所有数字和为target,则把a加入答案数组
            return;
        }
        if(st >= n)
            return;
        for(int i = st;i < n;i++){
            if(cur + ca[i] <= target){
                int num = 1;
                vector <int> b = a;
                while(cur + ca[i] * num <= target){   //数字可以重复,多次加入同一个数字
                    b.push_back(ca[i]);
                    dfs(i + 1,b,cur + ca[i] * num,target);  //i是起始位置 
                    num ++;
                }
            }
        }
    }
    vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
        n = candidates.size();
        ca = candidates;
        vector<int> a;
        sort(ca.begin(),ca.end());   //排序
        unique(ca.begin(), ca.end());   //去重
        dfs(0,a,0,target);  
        return ans;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值