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] 

     1 public class Solution {
     2     List<List<Integer>> result;
     3     public List<List<Integer>> combinationSum2(int[] num, int target) {
     4         result = new ArrayList<List<Integer>>();
     5         List<Integer> list = new ArrayList<Integer>();
     6         Arrays.sort(num);
     7         combination(num, 0, list, target);
     8         return result;
     9     }
    10     
    11         void combination(int[] num,int index,List<Integer> curr,int target) {
    12         if (target == 0) {
    13             result.add(new ArrayList<Integer>(curr));
    14 
    15         } else {
    16             for (int i = index; i < num.length; i++) {
    17                 if (i != index && num[i] == num[i - 1]) {
    18                     continue;
    19                 }
    20                 if (target >= num[i]) {
    21                     curr.add(num[i]);
    22                     combination(num, i + 1, curr, target - num[i]);
    23                     curr.remove(curr.size() - 1);
    24                 }
    25             }
    26         }
    27 
    28     }
    29     
    30 }
  • 相关阅读:
    选修课作业专栏
    js字符串和数组方法总结
    转Y-slow23原则(雅虎)
    前端优化总结和技巧(原创)
    阿里dom操作题
    基本的dom操作方法
    html5中的postMessage解决跨域问题
    mark一篇文章--用nodejs搭建一个本地反向代理环境
    html5语义化标签总结二
    转html5语义化标签总结一
  • 原文地址:https://www.cnblogs.com/birdhack/p/4204748.html
Copyright © 2011-2022 走看看