千家信息网

LeetCode如何解决组合总和问题

发表于:2025-02-01 作者:千家信息网编辑
千家信息网最后更新 2025年02月01日,这篇文章将为大家详细讲解有关LeetCode如何解决组合总和问题,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。题目给定一个无重复元素的数组 candidates 和
千家信息网最后更新 2025年02月01日LeetCode如何解决组合总和问题

这篇文章将为大家详细讲解有关LeetCode如何解决组合总和问题,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

题目

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:
所有数字(包括 target)都是正整数。解集不能包含重复的组合。
示例 1:
输入:candidates = [2,3,6,7], target = 7,所求解集为:[  [7],  [2,2,3]]
示例 2:
输入:candidates = [2,3,5], target = 8,所求解集为:[  [2,2,2,2],  [2,3,3],  [3,5]]
提示:
1 <= candidates.length <= 301 <= candidates[i] <= 200candidate 中的每个元素都是独一无二的。1 <= target <= 500
思路
回溯算法 + 剪枝
  • 输入: candidates = [2, 3, 6, 7],target = 7。

  • 候选数组里有 2,如果找到了组合总和为 7 - 2 = 5 的所有组合,再在之前加上 2 ,就是 7 的所有组合;

  • 同理考虑 3,如果找到了组合总和为 7 - 3 = 4 的所有组合,再在之前加上 3 ,就是 7 的所有组合,依次这样找下去。

代码
class Solution {    public List> combinationSum(int[] candidates, int target) {        int len = candidates.length;        List> res = new ArrayList<>();        if(len == 0){            return res;        }        Deque path = new ArrayDeque<>();        dfs(candidates,0,len,target,path,res);        return res;    }    public void dfs(int[] candidates,int begin,int len,int target,Deque path,List> res){        if(target < 0){            return;        }        if(target == 0){            res.add(new ArrayList<>(path));        }        for(int i = begin; i < len; i++){            path.addLast(candidates[i]);            dfs(candidates,i,len,target-candidates[i],path,res);            path.removeLast();        }    }}

关于"LeetCode如何解决组合总和问题"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

0