zoukankan      html  css  js  c++  java
  • 【leetcode刷题笔记】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 toT.

    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] 


    Combination Sum的差别就是上面红色的那行字,只要把递归时候的起点由i改为i+1即可,参见下列代码中高亮的部分:

    代码如下:

     1 public class Solution {
     2     private void combiDfs(int[] candidates,int target,List<List<Integer>> answer,List<Integer> numbers,int start){
     3         if(target == 0){
     4             answer.add(new ArrayList<Integer>(numbers));
     5             return;
     6         }
     7         
     8         int prev = -1;
     9         
    10         for(int i = start;i < candidates.length;i++){
    11             if(candidates[i] > target)
    12                 break;
    13             if(prev != -1 && prev == candidates[i])
    14                 continue;
    15             
    16             numbers.add(candidates[i]);
    17             combiDfs(candidates, target-candidates[i], answer, numbers,i+1);
    18             numbers.remove(numbers.size()-1);
    19             
    20             prev = candidates[i];
    21         }
    22     }
    23     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    24         List<List<Integer>> answer = new ArrayList<List<Integer>>();
    25         List<Integer> numbers = new ArrayList<Integer>();
    26         Arrays.sort(candidates);
    27         combiDfs(candidates, target, answer, numbers,0);
    28         
    29         return answer;
    30         
    31     }
    32 }
  • 相关阅读:
    NTDDI_VERSION,_WIN32_WINNT,WINVER,_WIN32_IE
    SOL_SOCKET, SO_KEEPALIVE
    荣幸的一天
    值得思考的一些东西
    一个flash前后台开源框架的的站点
    30个AS3开源项目
    [算法] doj 1066 最长上升子序列
    [算法] doj 1605 Common Subsequence 公共子序列
    华为EC321CDMA PCMICA 无线网卡Ubuntu下使用
    my_judged.cc 的初稿
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3860513.html
Copyright © 2011-2022 走看看