LeetCode_回溯算法_中等_39.组合总和

x33g5p2x  于2022-03-17 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(191)

1.题目

给你一个无重复元素的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的所有不同组合 ,并以列表形式返回。你可以按任意顺序返回这些组合。

candidates 中的同一个数字可以无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:
输入: candidates = [2], target = 1
输出: []

提示:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都互不相同
1 <= target <= 500

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum

2.思路

(1)回溯算法
思路参考回溯算法详解(修订版)。

3.代码实现(Java)

//思路1————回溯算法
class Solution {
    //res用于保存最终结果
    List<List<Integer>> res = new LinkedList<>();
    
    //track用于记录回溯的路径
    LinkedList<Integer> track = new LinkedList<>();
    
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtrack(candidates, 0, target, 0);
        return res;
    }
    
    public void backtrack(int[] candidates, int start, int target, int sum) {
        if (sum == target) {
            //找到目标组合,将其保存到res中
            res.add(new LinkedList<>(track));
            return;
        }
        if (sum > target) {
            //组合元素之和超过target,直接结束
            return;
        }
        //回溯算法框架
        for (int i = start; i < candidates.length; i++) {
            //做选择
            sum += candidates[i];
            track.add(candidates[i]);
            /*
                backtrack(路径, 选择列表)
                需要注意的是,数组 candidates 中的元素可以复用多次,所以在回溯树中往下进行查找的时候,起点仍然是 i
            */
            backtrack(candidates, i, target, sum);
            //撤销选择
            sum -= candidates[i];
            track.removeLast();
        }
    }
}

相关文章

微信公众号

最新文章

更多