• 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.
    • 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稍微改一下就行了

     1 import java.util.ArrayList;
     2 import java.util.Arrays;
     3 import java.util.List;
     4 import org.w3c.dom.CDATASection;
     5 
     6 public class Solution {
     7     public List<List<Integer>> combinationSum2(int[] num, int target) {
     8         Arrays.sort(num);
     9         List<List<Integer>> result = new ArrayList<List<Integer>>();
    10         getResult(result, new ArrayList<Integer>(), num, target, 0);
    11         
    12         return result;
    13     }
    14     
    15     private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
    16         if(target > 0){
    17             for(int i = start; i < candidates.length && target >= candidates[i]; i++){
    18                 cur.add(candidates[i]);
    19                 getResult(result, cur, candidates, target - candidates[i], i + 1);
    20                 cur.remove(cur.size() - 1);
    21                 
    22             }//for
    23         }//if
    24         else if(target == 0 && !result.contains(cur)){            
    25             result.add(new ArrayList<Integer>(cur));
    26             
    27         }//else if
    28     }
    29     
    30 }
  • 相关阅读:
    递归的形式过程
    c/c++程序员常见面试题分析(转)
    深入理解递归函数的调用过程(转)
    C语言union关键字
    中国象棋(java)
    求树中最低的公共祖先
    什么是Complement(补码)?
    LoadRunner,各协议之间的区别
    淘宝模板制作[店铺装修]学习过程+心得
    Tips of QTP
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4241112.html
Copyright © 2020-2023  润新知