Leetcode 题目解析之 Combination Sum II

举报
ruochen 发表于 2022/01/14 13:40:56 2022/01/14
【摘要】 Leetcode 题目解析之 Combination Sum II

Given a collection of candidate numbers © and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.
    For example, given candidate set 10,1,2,7,6,1,5 and target 8,

A solution set is:

1, 7

1, 2, 5

2, 6

1, 1, 6

  1. Combination Sum每个元素可以使用多次,所以递归是dfs(i, target - candidatesi, result, cur, candidates);
  2. Combination Sum II每个元素只能使用一次,所以递归是dfs(i + 1, target - candidatesi, rt, cur, candidates);因为解可能重复,所以使用set,最后转成list。
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) {
            return new ArrayList<List<Integer>>();
        }
        Set<List<Integer>> rt = new HashSet<List<Integer>>();
        ArrayList<Integer> cur = new ArrayList<Integer>();
        Arrays.sort(candidates);
        dfs(0, target, rt, cur, candidates);
        return new ArrayList<List<Integer>>(rt);
    }
    private void dfs(int start, int target, Set<List<Integer>> rt,
            ArrayList<Integer> cur, int[] candidates) {
        if (target == 0) {
            rt.add(new ArrayList<Integer>(cur));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            // candidates[i] > target,则递归结束,后面不可能是解
            if (candidates[i] > target) {
                return;
            }
            cur.add(candidates[i]);
            dfs(i + 1, target - candidates[i], rt, cur, candidates);
            cur.remove(cur.size() - 1);
        }
    }
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。