LeetCode Combination Sum DFS

本文介绍了一种使用深度优先搜索(DFS)解决组合求和问题的方法。通过对输入数据进行排序并利用递归DFS策略,文章详细阐述了如何找出所有可能的数的组合来达到目标值,同时提供了C++与Java两种语言的实现代码。

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

思想:

DFS。

由于每个字符可出现的次数不限,所以首先对数据集这里进行了排序,每一次往下一层前进的时候,起点还是i,直到不能前进,回退,i++。


class Solution {
public:
    //Combination Sum
    void dfs(vector<int> &candidates, int target, int start, vector<int> &value, vector<vector<int>> &res) {
        if(target == 0) {
            res.push_back(value);
            return;
        }
        for(int i = start; i < candidates.size(); i++) {
            if(target < candidates[i]) return;
            value.push_back(candidates[i]);
            dfs(candidates, target-candidates[i], i, value, res);
            value.pop_back();
        }
    }
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> res;
        vector<int> value;
        dfs(candidates,target,0,value,res);
        return res;
    }
};


java code:


public class Solution {
    /**
     * @param candidates: A list of integers
     * @param target:An integer
     * @return: A list of lists of integers
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // write your code here

        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> ans = new ArrayList<Integer>();

        Arrays.sort(candidates);

        dfs(res, ans, candidates, target, 0);

        return res;
    }

    public void dfs(List<List<Integer>> res, List<Integer> ans, int[] candidates, int target, int start) {
        if(target == 0) {
            res.add(new ArrayList<Integer>(ans));
            return;
        }
        
        int prev = -1;

        for(int i = start; i < candidates.length; ++i) {
            if(target < candidates[i]) return;
            
            if(prev != -1 && prev == candidates[i]) continue;
            ans.add(candidates[i]);
            dfs(res, ans, candidates, target - candidates[i], i);
            ans.remove(ans.size() - 1);
            prev = candidates[i];
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值