zoukankan      html  css  js  c++  java
  • LeetCode 377. Combination Sum IV

    原题链接在这里:https://leetcode.com/problems/combination-sum-iv/

    题目:

    Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

    Example:

    nums = [1, 2, 3]
    target = 4
    
    The possible combination ways are:
    (1, 1, 1, 1)
    (1, 1, 2)
    (1, 2, 1)
    (1, 3)
    (2, 1, 1)
    (2, 2)
    (3, 1)
    
    Note that different sequences are counted as different combinations.
    
    Therefore the output is 7.

    Follow up:
    What if negative numbers are allowed in the given array?
    How does it change the problem?
    What limitation we need to add to the question to allow negative numbers?

    题解:

    Let dp[i] denotes possible combinations that add up to i.

    Set some examples and find out that if there is nubmer smaller than i that i - num == j (num is the number of nums), then accumlate ways added up to j into dp[i].

    Initialize dp[0] =1, then all the numbers in nums will be initialized to 1 when it comes to dp[num-num].

    答案dp[target].

    If there is negative numbers allowed, there could be infinite possibilities. 

    e.g. target = 1, there is [-1, 1] in nums, then the possible ways could be -1+1+1, -1-1+1+1+1 ...

    If allowing negative numbers, there can't be any combiantion of neigatie numers + any combiantion of positive numbers == 0. 

    Time Complexity: O(target*nums.length).

    Space: O(target).

    AC Java:

     1 class Solution {
     2     public int combinationSum4(int[] nums, int target) {       
     3         int [] dp = new int[target+1];
     4         dp[0] = 1;
     5         
     6         for(int i = 1; i<=target; i++){
     7             for(int j = 0; j<nums.length; j++){
     8                 if(i>=nums[j]){
     9                     dp[i] += dp[i-nums[j]];
    10                 }
    11             }
    12         }
    13         return dp[target];
    14     }
    15 }

    跟着Combination SumCombination Sum IICombination Sum III.

    类似Climbing Stairs.

  • 相关阅读:
    数据结构----------------优先队列
    IDEA建立---- java web项目
    mysql 基础篇5(mysql语法---数据)
    数据库 基础篇4(mysql语法---表)
    数据库 基础篇3(mysql语法)
    数据库 基础篇2(mysql)
    vi保存搜索结果
    自定义修改connect rule
    xargs 的应用
    nfs,nis nobody的问题
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7675318.html
Copyright © 2011-2022 走看看