『Leetcode』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?

  首先对于Follow up的考虑,如果数组中出现负数怎么办?应该对问题做一些什么限制?

Answer: 负数的出现导致的最大问题是无穷解。即由于负数的加入,导致可能某些数字的组合出现和为0,从而导致无限的0加入并不影响最终结果。

对于限制,如果正负Integer同时出现并且不限制数目的话,那么无法避免这中无限的情况。因为只要同时存在正负整数(a & b = -c),总可以找到a,c的公倍数导致 m x a + n x b = 0

唯一可能的限制就在于combination的长度。

Solution

这是一个有放回的抽取实验,可以使用递归来实现,it[target] = nums[i] + it[target-nums[i]], 但是如果target过大而nums过小,则容易导致栈溢出。

而且,递归并没有办法保存状态,重复计算的工作很多。

递归代码如下:

public int combinationSum4(int[] nums, int target) {
    if(target < 0)
        return 0;
    if(target == 0)
        return 1;

    int ret = 0;
    for(int n: nums){
        ret += combinationSum4(nums,target-n);
    }
    return ret;
}

没有意外,Submission Result: Time Limit Exceeded

更为有效的方式是使用动态规划,状态转移方程与递归类似:

dpi=dp[inumi]

代码如下:

public class Solution {
    public int combinationSum4(int[] nums, int target) {
        int [] dp = new int[target+1];
        dp[0] = 1; //dp[i-i] = dp[0] = 1 make sure contains every number in array self.

        for(int i  = 1 ; i <= target; i ++){
            for(int n:nums){
                dp[i] += (i >= n) ? dp[i-n] : 0;
            }
        }
        return dp[target];
    }
}

参考Leetcode discuss可以做一些简单的优化。

public class Solution {
    public int combinationSum4(int[] nums, int target) {
        Arrays.sort(nums);
        int[] dp = new int[target + 1];
        dp[0] = 1;
        for (int i = 1; i < res.length; i++) {
            for (int num : nums) {
                if (num > i)
                    break;
                else
                dp[i] += dp[i-num];
            }
        }
        return dp[target];
    }
}

即,先将nums数组排序,然后在for循环中break一些分支。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值