zoukankan      html  css  js  c++  java
  • Combination Sum II 解答

    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.

  • 相关阅读:
    配置wpa_supplicant调试wifi linux下命令行连接wifi
    Android平台开发-WIFI 驱动移植 -- 详细
    明远智睿IMX6Q Android4.4.2移植USBWIFI(RTL8188EUS)
    android上USB Wifi调试记录
    Android wifi驱动的移植 realtek 8188
    CCF-CSP-201703-4-地铁修建
    CCF-CSP-201709-4-通信网络
    CCF-CSP-201409-4-最优配餐
    CCF/CSP-201612-4-压缩编码
    CCF/CSP-201612-3-权限查询
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4884535.html
Copyright © 2011-2022 走看看