首页 > 其他 > 详细

Combination Sum II 解答

时间:2015-10-16 11:31:43      阅读:198      评论:0      收藏:0      [点我收藏+]

Question

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.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 

Solution 1 -- DFS

Similar solution as Combination Sum.

 1 public class Solution {
 2     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
 3         Arrays.sort(candidates);
 4         List<List<Integer>> result = new ArrayList<List<Integer>>();
 5         for (int i = 0; i < candidates.length; i++) {
 6             List<Integer> record = new ArrayList<Integer>();
 7             record.add(candidates[i]);
 8             dfs(candidates, i, target - candidates[i], result, record);
 9         } 
10         return result;
11     }
12     private void dfs(int[] candidates, int start, int target, List<List<Integer>> result, List<Integer> record) {
13         if (target < 0)
14             return;
15         if (target == 0) {
16             if (!result.contains(record))
17                 result.add(new ArrayList<Integer>(record));
18             return;
19         }
20         // Because C can only be used once, we start from "start + 1"
21         for(int i = start + 1; i < candidates.length; i++) {
22             record.add(candidates[i]);
23             dfs(candidates, i, target - candidates[i], result, record);
24             record.remove(record.size() - 1);
25         }
26     }
27 }

Solution 2 -- BFS

To avoid duplicates in array, we can create a class:

class Node {

  public int val;

  public int index;

}

And put these node in arraylists for BFS.

Combination Sum II 解答

原文:http://www.cnblogs.com/ireneyanglan/p/4884535.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!