【回溯】Leetcode 39. 组合总和【中等】

组合总和

给你一个 无重复元素 的整数数组 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 。
仅有这两种组合。

解题思路

  • 1、使用回溯算法来生成所有不同的组合。
  • 2、对于每个数字,可以选择将其加入当前组合或者不加入当前组合。
  • 3、使用递归回溯的方法,尝试加入每个数字,并继续向后搜索。
  • 4、当前组合的和等于目标数target时,将当前组合加入结果集。

java实现

public class CombinationSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(candidates, target, 0, new ArrayList<>(), 0, result);
        return result;
    }

    private void backtrack(int[] candidates, int target, int start, List<Integer> combination, int sum, List<List<Integer>> result) {
        if (sum == target) {
            result.add(new ArrayList<>(combination));
            return;
        }
        if (sum > target) {
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            combination.add(candidates[i]);
            backtrack(candidates, target, i, combination, sum + candidates[i], result);
            combination.remove(combination.size() - 1);
        }
    }

    public static void main(String[] args) {
        CombinationSum solution = new CombinationSum();
        int[] candidates = {2, 3, 6, 7};
        int target = 7;
        List<List<Integer>> combinations = solution.combinationSum(candidates, target);
        System.out.println("All possible combinations:");
        for (List<Integer> combination : combinations) {
            System.out.println(combination);
        }
    }
}

时间空间复杂度

  • 时间复杂度:由于回溯算法的性质,最坏情况下时间复杂度为O(N^target),其中N是candidates数组的长度,target是目标数。

  • 空间复杂度:O(target),递归调用栈的深度为目标数target。

相关推荐

  1. 回溯Leetcode 39. 组合总和中等

    2024-04-13 08:44:01       19 阅读
  2. 组合总和(Lc39)——排序+剪枝+回溯

    2024-04-13 08:44:01       9 阅读
  3. LeetCode 0039.组合总和回溯 + 剪枝

    2024-04-13 08:44:01       12 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-13 08:44:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-13 08:44:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-13 08:44:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-13 08:44:01       20 阅读

热门阅读

  1. 蓝桥杯---数组分割

    2024-04-13 08:44:01       21 阅读
  2. 蓝桥杯考前准备— — c/c++

    2024-04-13 08:44:01       17 阅读
  3. 数据库:SQL分类之DML详解

    2024-04-13 08:44:01       18 阅读
  4. Scanner类的使用步骤

    2024-04-13 08:44:01       16 阅读
  5. 【ssh】群晖 ssh clone github 远程仓库

    2024-04-13 08:44:01       15 阅读
  6. ClickHouse 与 MySQL 介绍与比较

    2024-04-13 08:44:01       18 阅读