码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode——组合总和 Ⅳ

时间:2020-06-02 11:09:57      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:length   组成   可重复   leetcode   背包问题   正整数   整数   序列   元素   

Q:给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。

示例:

nums = [1, 2, 3]
target = 4

所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

请注意,顺序不同的序列被视作不同的组合。
因此输出为 7。

A:
1.回溯法
超时。

    private int sum;

    public int combinationSum4(int[] nums, int target) {
        if (target == 0)
            return 1;
        if (nums.length == 0)
            return 0;
        sum = 0;
        combination(nums, target);
        return sum;
    }

    private void combination(int[] nums, int target) {
        if (target == 0) {
            sum++;
            return;
        }
        for (Integer i : nums) {
            target -= i;
            if (target >= 0)
                combination(nums, target);
            target += i;
        }
    }

2.动态规划
完全背包问题,元素可重复,不考虑顺序。

    public int combinationSum4(int[] nums, int target) {
        if (target == 0)
            return 1;
        if (nums.length == 0)
            return 0;
        int[] dp = new int[target + 1];
        dp[0] = 1;
        for (int i = 1; i <= target; i++) {
            for (Integer num : nums) {
                if (i - num >= 0) {
                    dp[i] += dp[i - num];
                }
            }
        }
        return dp[target];
    }

LeetCode——组合总和 Ⅳ

标签:length   组成   可重复   leetcode   背包问题   正整数   整数   序列   元素   

原文地址:https://www.cnblogs.com/xym4869/p/13029744.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!