15.Backpack VI

http://www.lintcode.com/zh-cn/problem/backpack-vi/

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

你可能感兴趣的:(15.Backpack VI)