[LintCode] Backpack VI 背包之六

简介:

Given an integer array nums with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

 Notice

The different sequences are counted as different combinations.

Example

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

The possible combination ways are:
[1, 1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[2, 1, 1]
[2, 2]
[4]

return 6

不太懂这题名称为啥叫backpack,LeetCode上的原题,请参见我之前的博客Combination Sum IV 。

解法一:

class Solution {
public:
    /**
     * @param nums an integer array and all positive numbers, no duplicates
     * @param target an integer
     * @return an integer
     */
    int backPackVI(vector<int>& nums, int target) {
        vector<int> dp(target + 1, 0);
        dp[0] = 1;
        for (int i = 1; i <= target; ++i) {
            for (auto a : nums) {
                if (a <= i) {
                    dp[i] += dp[i - a];
                }
            }
        }
        return dp.back();
    }
};

解法二:

class Solution {
public:
    /**
     * @param nums an integer array and all positive numbers, no duplicates
     * @param target an integer
     * @return an integer
     */
    int backPackVI(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 (auto a : nums) {
                if (a > i) break;
                dp[i] += dp[i - a];
            }
        }
        return dp.back();
    }
};

本文转自博客园Grandyang的博客,原文链接:背包之六[LintCode] Backpack VI ,如需转载请自行联系原博主。

相关文章
|
9月前
|
机器学习/深度学习 Java
【Java每日一题,dfs】[USACO1.5]八皇后 Checker Challenge
【Java每日一题,dfs】[USACO1.5]八皇后 Checker Challenge
|
10月前
|
Linux
攻防世界-Reverse新手区WP--maze
攻防世界-Reverse新手区WP--maze
40 0
|
10月前
|
Linux
攻防世界-Reverse区WP--maze
攻防世界-Reverse区WP--maze
55 0
|
11月前
|
Java
汉诺塔问题(Hanoi Tower)--递归典型问题--Java版(图文详解)
汉诺塔问题(Hanoi Tower)--递归典型问题--Java版(图文详解)
|
12月前
BUUCTF--Reverse--easyre(非常简单的逆向)WP
BUUCTF--Reverse--easyre(非常简单的逆向)WP
每日一题---27. 移除元素[力扣][Go]
每日一题---27. 移除元素[力扣][Go]
每日一题---27. 移除元素[力扣][Go]
每日一题---1005. K 次取反后最大化的数组和[力扣][Go]
每日一题---1005. K 次取反后最大化的数组和[力扣][Go]
每日一题---1005. K 次取反后最大化的数组和[力扣][Go]
每日一题---1034. 边界着色[力扣][Go]
每日一题---1034. 边界着色[力扣][Go]
每日一题---1034. 边界着色[力扣][Go]
每日一题---748. 最短补全词[力扣][Go]
每日一题---748. 最短补全词[力扣][Go]
每日一题---748. 最短补全词[力扣][Go]
每日一题---1380. 矩阵中的幸运数[力扣][Go]
每日一题---1380. 矩阵中的幸运数[力扣][Go]
每日一题---1380. 矩阵中的幸运数[力扣][Go]