【DFS】组合总数

一、题目

. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=N7T8https://leetcode.cn/problems/combination-sum/description/

二、题解

枚举每个位置所有的可能,当前总和等于target时收集答案,如果直接每个位置都考虑n种选法,那么答案是包含重复的,所以我们只需要选择当前位置后面的元素进行组合

class Solution {
public:
    vector<vector<int>> res;  // 结果集合
    vector<int> path, a;      // 路径path, a是全局化candidates
    int n, t, sum;            // n是candidates的元素个数,t是全局化后的 target, sum用于记录dfs过程中路径上的值


    void dfs(int u) {
        if (sum > t) return;   // 如果当前路径总和已经超过目标值则结束
        
        for (int i = u; i < n; i++){ // 开始枚举当前位置及以后的元素作为当前位置的值
            sum += a[i];       // 选择i位置
            path.push_back(a[i]);

            if (sum == t) res.push_back(path); // 如果等于就收集答案
            else dfs(i);        // 不等于则dfs下一层
            
            path.pop_back();    // 恢复现场
            sum -= a[i]; 
        }
    }

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        a = candidates;
        n = a.size(), t = target;   // 全局化
        dfs(0);
        return res;
    }
};
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值