leetcode 40. Combination Sum II
来源:互联网 发布:网络与端口有何区别 编辑:程序博客网 时间:2024/06/04 06:27
import java.util.ArrayList;import java.util.Arrays;import java.util.List;//Given a collection of candidate numbers (C) 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.//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]//]public class Solution { public static void main(String[] aargs){int target = 8;int[] candidates = {10,1,2,7,6,1,5};List<List<Integer>> result = combinationSum2(candidates, target);System.out.println(result);} public static List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> result = new ArrayList<List<Integer>>(); Arrays.sort(candidates); List<Integer> ans = new ArrayList<Integer>(); resolve(candidates, target, result, ans, -1); return result; } public static void resolve(int[] candidates, int target, List<List<Integer>> result, List<Integer> ans, int pos) { for(int i = pos+1;i<candidates.length;i++){//与上题很像,只是每次迭代从candidates中的下一个元素开始即可 if(target == candidates[i]){ ans.add(candidates[i]); if(result.contains(ans)){//避免重复 ans.remove(ans.size()-1); return; } result.add(new ArrayList<Integer>(ans));//new ArrayList<Iteger>的作用是使结果列表的值不随之后ans的改变而改变 ans.remove(ans.size()-1); return; } if(target > candidates[i]){ ans.add(candidates[i]); resolve(candidates, target-candidates[i], result, ans, i);//candidates,减去当前元素后的target,结果列表,当前整形元素列表,当前检索到了什么位置 ans.remove(ans.size()-1); }else{ return; } } } }
0 0
- [LeetCode]40.Combination Sum II
- LeetCode --- 40. Combination Sum II
- LeetCode 40.Combination Sum II
- [Leetcode] 40. Combination Sum II
- LeetCode 40. Combination Sum II
- [leetcode] 40. Combination Sum II
- 40. Combination Sum II LeetCode
- leetcode 40. Combination Sum II
- Leetcode 40. Combination Sum II
- LeetCode 40. Combination Sum II
- leetcode 40. Combination Sum II
- LeetCode 40. Combination Sum II
- LeetCode 40. Combination Sum II
- LeetCode *** 40. Combination Sum II
- 【LeetCode】40. Combination Sum II
- leetcode 40. Combination Sum II
- LeetCode - 40. Combination Sum II
- [LeetCode] 40. Combination Sum II
- redis设置启动服务
- Java EE核心架构
- awk命令详解
- 上拉刷新,下拉加载
- Android开发中的程序调试
- leetcode 40. Combination Sum II
- 4.4、Android Studio在命令行运行Gradle
- ubuntu下转ttf, otf为woff文件
- Hadoop集群环境搭建
- UITextField 与 键盘
- 常用正则表达式示例
- android studio 的 Error occurred during initialization of VM Could not reserve enough space fo 解决办法
- [LC 94 144 145]Binary Tree Traversal ( preorder, inorder,postorder)
- 数据结构复习——线性表的链式存储实现(单向链表)