zoukankan      html  css  js  c++  java
  • [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();
        }
    };
  • 相关阅读:
    找水王
    第十四周学习记录
    第十三周学习记录
    第十二周学习记录
    序列化
    哪个元素出发事件
    阻止默认行为-event.preventDefault();
    阻止时间冒泡 -event.stopPropagation();
    HTML5的LocalStorage和sessionStorage的使用 -缓存
    同步加载、异步加载、延迟加载
  • 原文地址:https://www.cnblogs.com/grandyang/p/5743719.html
Copyright © 2011-2022 走看看