Combination Sum II
来源:互联网 发布:小蜜蜂软件官方网 编辑:程序博客网 时间:2024/06/04 00:43
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inC where the candidate numbers sums toT.
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 target8
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6]]思路:一次只能算一次,index要从下一个开始,还要去重,因为[1,1,2,5] 如果不去重,会出现[1,2,5] [1,2,5] 两次,所以要去重。
public class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> lists = new ArrayList<List<Integer>>(); if(candidates == null || candidates.length == 0){ return lists; } List<Integer> list = new ArrayList<Integer>(); Arrays.sort(candidates); collect(candidates, lists, list, target, 0 , 0); return lists; } public void collect(int[] candidates, List<List<Integer>> lists, List<Integer> list, int target, int sum, int index){ if(sum > target) return; if(sum == target){ lists.add(new ArrayList<Integer>(list)); return; } for(int i=index; i<candidates.length; i++){ if(i>index && candidates[i] == candidates[i-1]){ continue; } sum += candidates[i]; list.add(candidates[i]); collect(candidates, lists, list, target, sum, i+1); list.remove(list.size()-1); sum -= candidates[i]; } }}
0 0
- Combination Sum && Combination Sum II
- Combination Sum Combination Sum II
- Combination Sum II
- LeetCode: Combination Sum II
- LeetCode: Combination Sum II
- [LeetCode]Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- Combination Sum II
- [LeetCode] Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- Combination Sum II
- LeetCode: Combination Sum II
- Combination Sum II
- leetcode Combination Sum II
- Combination Sum II
- [LeetCode]Combination Sum II
- POJ 3268 Silver Cow Party
- MySQL修改root密码的多种方法
- C# for Unity快速入门-C#语言入门(B)
- Android studio怎么直接对apk签名?
- 线程、进程
- Combination Sum II
- 什么是脏读、不可重复读、幻读
- python的urllib2和urllib爬虫及区别
- 实习杂记(30):eclipse小知识点积累
- Java编程风格节选
- python matplotlib入门
- 根据wsdl生成客户端:Use of SOAP Encoding is not supported
- C/C++_
- iOS面试系列5