码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 40: Combination Sum II

时间:2017-11-07 14:33:30      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:get   for   span   algorithm   clu   ttl   which   and   script   

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

标签:get   for   span   algorithm   clu   ttl   which   and   script   

原文地址:http://www.cnblogs.com/liangmou/p/7798496.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!