面试算法-115-组合总和

题目

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

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        dfs(candidates, 0, target, path, result);
        return result;
    }

    public void dfs(int[] candidates, int index, int target, LinkedList<Integer> path, List<List<Integer>> result) {
        if (target == 0) {
            result.add(new LinkedList<>(path));
            return;
        }
        if (target < 0) {
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            path.add(candidates[i]);
            dfs(candidates, i, target - candidates[i], path, result);
            path.removeLast();
        }
    }
}

相关推荐

  1. 面试算法-115-组合总和

    2024-03-28 18:40:02       18 阅读
  2. 面试算法-117-组合总和 III

    2024-03-28 18:40:02       14 阅读
  3. 面试算法-113-打家劫舍

    2024-03-28 18:40:02       19 阅读
  4. 高频算法面试总结

    2024-03-28 18:40:02       32 阅读
  5. 算法题】40. 组合总和 II

    2024-03-28 18:40:02       29 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-28 18:40:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-28 18:40:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-28 18:40:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-28 18:40:02       20 阅读

热门阅读

  1. C#___锁(lock)

    2024-03-28 18:40:02       17 阅读
  2. 数据分类分级赋能企业数据安全建设(附下载)

    2024-03-28 18:40:02       23 阅读
  3. Sprinboot vue elementui考勤管理系统

    2024-03-28 18:40:02       24 阅读
  4. 快速部署docker-compose环境

    2024-03-28 18:40:02       21 阅读
  5. c++(Qt) 编码转换

    2024-03-28 18:40:02       18 阅读
  6. go中函数与方法的区别与go中关于面向对象理解

    2024-03-28 18:40:02       21 阅读
  7. 现在做视频号小店晚吗?平台发展趋势如何?

    2024-03-28 18:40:02       22 阅读