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 }
  • 相关阅读:
    springboot、监听器
    springboot、拦截器
    Thymeleaf模板引擎
    springboot-banner.txt
    springboot,swagger2
    springboot 热部署
    判断是否为微信环境下打开的网页
    后台接收json数据
    ios 面试题
    iOS 适配问题
  • 原文地址:https://www.cnblogs.com/birdhack/p/4204748.html
Copyright © 2011-2022 走看看