标签:问题 des bsp [] .so example return oid http
题目:
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:
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]
链接: http://leetcode.com/problems/combination-sum-ii/
4/14/2017
18ms, 92%
出现的问题
1. 第6行排序不要遗忘
2. 第17行最开始的判断为什么是i > pos?我直接想想不出来,但是可以尝试着解释[1,1,2,5,6,7,10]中[1,1,6]和[1,7]第一组为什么可以有2个1?因为这两个1不是在同一层加进去的,所以可以视为不同的元素,而[1,7]不能重复是因为当时2个1是在同一层,pos值是一样的。
3. 时间复杂度?
1 public class Solution { 2 public List<List<Integer>> combinationSum2(int[] candidates, int target) { 3 List<List<Integer>> ret = new ArrayList<>(); 4 if (candidates.length == 0) return ret; 5 List<Integer> temp = new ArrayList<Integer>(); 6 Arrays.sort(candidates); 7 enumerate(candidates, target, ret, temp, 0); 8 return ret; 9 } 10 11 private void enumerate(int[] candidates, int target, List<List<Integer>> ret, List<Integer> temp, int pos) { 12 if (target == 0) { 13 ret.add(new ArrayList<Integer>(temp)); 14 return; 15 } 16 for (int i = pos; i < candidates.length; i++) { 17 if (i > pos && candidates[i] == candidates[i - 1]) continue; 18 if (candidates[i] > target) break; 19 temp.add(candidates[i]); 20 enumerate(candidates, target - candidates[i], ret, temp, i + 1); 21 temp.remove(temp.size() - 1); 22 } 23 } 24 }
更多讨论:
https://discuss.leetcode.com/category/48/combination-sum-ii
标签:问题 des bsp [] .so example return oid http
原文地址:http://www.cnblogs.com/panini/p/6713358.html