背包问题

http://www.lintcode.com/zh-cn/…

给出一个都是正整数的数组 nums,其中没有重复的数。从中找出所有的和为 target 的组合个数。

注意事项

一个数可以在组合中出现多次。
数的顺序不同则会被认为是不同的组合。

样例
给出 nums = [1, 2, 4], target = 4
可能的所有组合有:

[1, 1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[2, 1, 1]
[2, 2]
[4]
返回 6

#include <stdio.h>
#include <string>
#include <vector>
#include <algorithm>

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

};

int main(int, char**) {
    Solution solution;
    std::vector<int> nums = { 1, 2, 4 };
    int target = 4;
    printf("%d\n", solution.backPackVI(nums, target));
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *