Leetcode 40: Combination Sum II
Posted Keep walking
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 40: Combination Sum II相关的知识,希望对你有一定的参考价值。
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] ]
The algorithm below beats 100% C# answers.
1 public class Solution { 2 public IList<IList<int>> CombinationSum2(int[] candidates, int target) { 3 // idea 1: brute force, generate all possible combination which has 2^N possibilities and check whether 4 // each combination‘s sum equals target. The time complexity is super high though. 5 6 // idea 2: backtracking, potential optimazition, sort the candidates first. Memorization probably will help 7 // but it‘s a little bit hard to check dup output 8 var result = new List<IList<int>>(); 9 10 Array.Sort(candidates); 11 if (candidates.Length == 0 || target < candidates[0]) return result; 12 13 DFS(candidates, target, 0, 0, new List<int>(), result); 14 15 return result; 16 } 17 18 private void DFS(int[] candidates, int target, int sum, int start, IList<int> res, IList<IList<int>> result) 19 { 20 if (target == sum) 21 { 22 result.Add(new List<int>(res)); 23 return; 24 } 25 26 if (target < sum || start >= candidates.Length) return; 27 28 for (int i = start; i < candidates.Length; i++) 29 { 30 if (sum + candidates[i] > target) 31 { 32 break; 33 } 34 35 while (i > start && i < candidates.Length &&candidates[i] == candidates[i - 1]) 36 { 37 i++; 38 } 39 40 if (i >= candidates.Length) 41 { 42 return; 43 } 44 45 res.Add(candidates[i]); 46 DFS(candidates, target, sum + candidates[i], i + 1, res, result); 47 res.RemoveAt(res.Count - 1); 48 } 49 } 50 }
以上是关于Leetcode 40: Combination Sum II的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 40. Combination Sum II
[LeetCode] 40. Combination Sum II
[LeetCode] 40. Combination Sum II
[array] leetcode - 40. Combination Sum II - Medium