377. 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.

这道题最直观的做法就是递归搜索:

var combinationSum4 = function(nums, target) {
    const totalLen = nums.length;
    let result = 0;
    const search = function(nums, target) {
        for(let i=0;i<totalLen;i++) {
            if(nums[i] === target) {
                result++;
                return;
            }
            else if(nums[i] < target) {
                search(nums, target-nums[i]);
            }
            else {
                return;
            }
        }
    };
    search(nums, target);
    return result;
};

很是暴力直接,当target与数组里的元素差距不大时运行得非常好,但是遇到像是var nums = [1, 2, 3], target = 32;这样的测试用例时,会耗费2s左右的时间,耗时过长。回到题目中,有个解法提示,让我们考虑下动态规划。
  例如用例为var nums = [1, 2, 3], target = 4;当计算target为3时,它的解法数量可以为dp[3] += dp[3-x],也就是说3可以拆分为1+x,2+x,3+x,这里dp[x]表示target为x时的解法。那么对于i从1到target,如果i不小于nums中的数,则可以用dp[i] += dp[i-x]表示对应的解数。
  上代码:

var combinationSum4 = function (nums, target) {
    const dp = [1];
    nums.sort((a, b) => { return a - b; })
    for (let i = 1; i <= target; i++) {
        dp.push(0);
        for (let num of nums) {
            if (num <= i) {
                dp[i] += dp[i - num];
            }
            else {
                break;
            }
        }
    }
    return dp[target];
};

时间复杂度为O(n^2),空间复杂度O(n)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 本题发现用dfs是要超时的,看了别人的答案发现是要dp。 dp[i] 表示target = i 时的组合种数。所...
    yangqi916阅读 392评论 0 0
  • 题目 Given an integer array with all positive numbers and n...
    Eazow阅读 910评论 0 1
  • 《ijs》速成开发手册3.0 官方用户交流:iApp开发交流(1) 239547050iApp开发交流(2) 10...
    叶染柒丶阅读 5,321评论 0 7
  • 脚步轻轻 寻着一路淡香便来了 偷爬上姑娘羞怯的眼 又溜去呱呱的幼孩身边 为静默的逝去抹掉一把泪 还和痴痴笑的傻子玩...
    木迎阅读 262评论 0 4