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 }
  • 相关阅读:
    Django-分页器
    Django-利用Form组件和ajax实现的注册
    Django之auth用户认证
    django之跨表查询及添加记录
    Django之queryset API
    bootstrip CSS
    bootstrip安装
    Django之环境安装
    前端之jQuery基础篇02-事件
    前端之jQuery基础篇
  • 原文地址:https://www.cnblogs.com/birdhack/p/4204748.html
Copyright © 2011-2022 走看看