Leetcode 40. 组合总和 II

网友投稿 524 2022-11-16

Leetcode 40. 组合总和 II

Leetcode 40. 组合总和 II

题目传送地址: ​​static List> combinationSum2(int[] candidates, int target) { Set set = new HashSet<>(); //先排序 Arrays.sort(candidates); List> result = new ArrayList<>(); for (int i = 0; i < candidates.length; i++) { if (candidates[i] > target) { continue; } List> combination = combination(candidates, i, target); if (!combination.isEmpty()) { for (List list : combination) { if (set.add(Arrays.toString(list.toArray()))) { result.add(list); } } } } return result; } //以索引位置i处的元素结尾,且组合出来的结果=target public static List> combination(int[] candidates, int i, int target) { List> result = new ArrayList<>(); if (target == 0) { result.add(Arrays.asList()); return result; } if (target == candidates[i]) { result.add(Arrays.asList(target)); return result; } if (target - candidates[i] < 0) { // return result; } int lastIndex = i - 1; if (lastIndex == 0 && candidates[0] == target - candidates[i]) { result.add(Arrays.asList(candidates[0], candidates[1])); return result; } int repeatCount = 1; while (lastIndex > 0 && candidates[lastIndex] == candidates[i]) { lastIndex--; repeatCount++; } for (int m = 1; m <= repeatCount; m++) { int n = lastIndex; while (n >= 0) { List> combination = combination(candidates, n, target - m * candidates[i]); for (List list : combination) { List integers = new ArrayList<>(list); for (int j = 0; j < m; j++) { integers.add(candidates[i]); } result.add(integers); } n--; } } return result; }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Leetcode45. 跳跃游戏 II
下一篇:1301_两种方式为开发板增加串口监控功能
相关文章

 发表评论

暂时没有评论,来抢沙发吧~