[LeetCode] 377. Combination Sum IV 组合之和 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?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
解法1:递归。按照前面I, II的思路用递归来解,会TLE,比如:OJ一个test case为[4,1,2] 32,结果是39882198,用递归需要好几秒时间。
解法2:动态规划DP来解。这道题类似于322. Coin Change ,建一个一维数组dp,dp[i]表示目标数target为i时解的个数,从1遍历到target,对于每一个数i,遍历nums数组,如果i>=x, dp[i] += dp[i - x]。比如[1,2,3] 4,当计算dp[3]时,3可以拆分为1+x,而x即为dp[2],3也可以拆分为2+x,x为dp[1],3同样可以拆为3+x,x为dp[0],把所有情况加起来就是组成3的所有解。
Java: Recursive
public int combinationSum4(int[] nums, int target) {
    if (target == 0) {
        return 1;
    }
    int res = 0;
    for (int i = 0; i < nums.length; i++) {
        if (target >= nums[i]) {
            res += combinationSum4(nums, target - nums[i]);
        }
    }
    return res;
}
Java:
private int[] dp;
public int combinationSum4(int[] nums, int target) {
    dp = new int[target + 1];
    Arrays.fill(dp, -1);
    dp[0] = 1;
    return helper(nums, target);
}
private int helper(int[] nums, int target) {
    if (dp[target] != -1) {
        return dp[target];
    }
    int res = 0;
    for (int i = 0; i < nums.length; i++) {
        if (target >= nums[i]) {
            res += helper(nums, target - nums[i]);
        }
    }
    dp[target] = res;
    return res;
}
Java:
public int combinationSum4(int[] nums, int target) {
    int[] comb = new int[target + 1];
    comb[0] = 1;
    for (int i = 1; i < comb.length; i++) {
        for (int j = 0; j < nums.length; j++) {
            if (i - nums[j] >= 0) {
                comb[i] += comb[i - nums[j]];
            }
        }
    }
    return comb[target];
}
Java:
class Solution {
    public int combinationSum4(int[] nums, int target) {
        if(nums==null || nums.length==0)
            return 0;
        int[] dp = new int[target+1];
        dp[0]=1;
        for(int i=0; i<=target; i++){
           for(int num: nums){
               if(i+num<=target){
                   dp[i+num]+=dp[i];
               }
           }
        }
        return dp[target];
    }
} 
Python:
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] * (target+1)
dp[0] = 1
nums.sort() for i in xrange(1, target+1):
for j in xrange(len(nums)):
if nums[j] <= i:
dp[i] += dp[i - nums[j]]
else:
break return dp[target]
Python:
class Solution(object):
def combinationSum4(self, nums, target):
nums, combs = sorted(nums), [1] + [0] * (target)
for i in range(target + 1):
for num in nums:
if num > i: break
if num == i: combs[i] += 1
if num < i: combs[i] += combs[i - num]
return combs[target]
C++:
class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<int> dp(target + 1, 0);
        dp[0] = 1;
        sort(nums.begin(), nums.end());
        for (int i = 1; i <= target; ++i) {
            for (int j = 0; j < nums.size() && nums[j] <= i; ++j) {
                dp[i] += dp[i - nums[j]];
            }
        }
        return dp[target];
    }
};  
类似题目:
[LeetCode] 322. Coin Change 硬币找零
[LeetCode] 39. Combination Sum 组合之和
[LeetCode] 40. Combination Sum II 组合之和 II
[LeetCode] 216. Combination Sum III 组合之和 III
All LeetCode Questions List 题目汇总
[LeetCode] 377. Combination Sum IV 组合之和 IV的更多相关文章
- [LeetCode] 216. Combination Sum III 组合之和 III
		
Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...
 - [leetcode]40. Combination Sum II组合之和之二
		
Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...
 - [LeetCode] 40. Combination Sum II 组合之和 II
		
Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...
 - [LeetCode] 40. Combination Sum II 组合之和之二
		
Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...
 - [LeetCode] 377. Combination Sum IV 组合之和之四
		
Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...
 - [LeetCode] Combination Sum III 组合之和之三
		
Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...
 - [LeetCode] Combination Sum II 组合之和之二
		
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
 - LeetCode OJ:Combination Sum II (组合之和 II)
		
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
 - 377 Combination Sum IV 组合之和 IV
		
Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...
 
随机推荐
- lca:异象石(set+dfs序)
			
题目:https://loj.ac/problem/10132 #include<bits/stdc++.h> using namespace std; ,N,k=,head[]; str ...
 - 开发Electron可能用到的工具
			
nodejs:搭载谷歌v8内核的高性能的node环境npm:包管理工具webpack:模块打包器jQuery:js必备库Bootstrap:css必备库react:用于构建用户界面的库vue:构建数据 ...
 - shortcuts for contructor 创建对象捷径
 - Convert 输入字符串的格式不正确
			
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...
 - Task 使用方法
			
Task的使用方法 1. 调用无参数.无返回值方法 private void button1_Click(object sender, EventArgs e) { Task task = new T ...
 - eclipse 配置python环境 json 插件
			
windows->install new software add 配置python 环境: name:pydev(可随意写) url:http://pydev.org/updates/ (如果 ...
 - S1_搭建分布式OpenStack集群_03 Mysql、MQ、Memcached、ETCD安装配置
			
一.安装mysql(contorller)controller ~]# yum -y install mariadb mariadb-server python2-PyMySQL 配置my.cnf文件 ...
 - 使用nginx 正向代理暴露k8s service && pod ip 外部直接访问
			
有时在我们的实际开发中我们希望直接访问k8s service 暴露的服务,以及pod的ip 解决方法,实际上很多 nodeport ingress port-forword 实际上我们还有一种方法:正 ...
 - hasura skor 一个pg 的event trigger 扩展
			
hasura skor 是一个hasura 团队早期的event triggerpg 扩展,新的推荐使用graphql engine 参考架构 缺点 只有在skor 运行的时候,数据才可以被捕捉处理 ...
 - IIS 站点配置文件
			
IIS 站点配置文件 C:/Windows/System32/inetsrv/config/applicationHost.config 配置文件示例: <system.application ...