Climbing Stairs

喜夏-厌秋 提交于 2020-02-17 11:51:44

原题链接在这里: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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!