zoukankan      html  css  js  c++  java
  • [leetcode]39. Combination Sum组合之和

    Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

    The same repeated number may be chosen from candidates unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    Example 1:

    Input: candidates = [2,3,6,7], target = 7,
    A solution set is:
    [
      [7],
      [2,2,3]
    ]
    

    Example 2:

    Input: candidates = [2,3,5], target = 8,
    A solution set is:
    [
      [2,2,2,2],
      [2,3,3],
      [3,5]
    ]

    题意:

    给定一个集合以及一个值target,找出所有加起来等于target的组合。(每个元素可以用无数次)

    Solution1: Backtracking

    code: 

     1 /*
     2 Time: O(n!)   factorial,  n!=1×2×3×…×n   
     3 Space: O(n)  coz n levels in stack for recrusion
     4 */
     5 
     6 class Solution {
     7     public List<List<Integer>> combinationSum(int[] nums, int target) {
     8         Arrays.sort(nums); // 呼应dfs的剪枝动作
     9         List<List<Integer>> result = new ArrayList<>(); 
    10         List<Integer> path = new ArrayList<>(); 
    11         dfs(nums, path, result, target, 0);
    12         return result;
    13     }
    14 
    15     private static void dfs(int[] nums, List<Integer> path, 
    16                             List<List<Integer>> result, int remain, int start) {
    17         // base case 
    18         if (remain == 0) {  
    19             result.add(new ArrayList<Integer>(path));
    20             return;
    21         }
    22         
    23         for (int i = start; i < nums.length; i++) {  
    24             if (remain < nums[i]) return; //基于 Arrays.sort(nums); 
    25             path.add(nums[i]); 
    26             dfs(nums, path, result, remain - nums[i], i);
    27             path.remove(path.size() - 1);  
    28         }
    29     }
    30 }
  • 相关阅读:
    家庭作业 3.66
    存储器层次结构
    PHP empty()函数说明---用了N遍了就是记不住
    如何让mysql的自动递增的字段重新从1开始呢?(
    dirname(__FILE__) 的使用总结
    又回来了
    Ecshop 后台增加一个左侧列表菜单menu菜单的方法
    用PHP上传文件时$_FILES中error返回值详解
    ECSHOP站内页面跳转,避免死链
    比特币Bitcoin-qt客户端加密前后如何导入导出私钥?
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10705497.html
Copyright © 2011-2022 走看看