一些dp问题合集

518. Coin Change 2

解法见 👉 518. Coin Change 2

322. Coin Change

解法见 👉 322. Coin Change

377. Combination Sum IV

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

例子:

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

The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

Note that different sequences are counted as different combinations.

Therefore the output is 7.

代码:

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<unsigned 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 (i < a) break;
                dp[i] += dp[i - a];
            }
        }
        return dp.back();
    }
};



279. Perfect Squares

问题描述:
Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.
For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

例子:

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

代码:

class Solution {
public:
    int numSquares(int n) {
        vector<int> square_nums;
        for (int i = floor(sqrt(n)); i >= 1; i--) square_nums.push_back(i * i);

        vector<int> dp(n + 1, n + 1);
        dp[0] = 0;
        for (int i = 1; i <= n; i++) {
            for (auto e : square_nums) {
                if (e <= i) dp[i] = min(dp[i], dp[i - e] + 1);
            }
        }

        return dp[n];
    }
};
posted @ 2021-02-25 16:20  nullxjx  阅读(75)  评论(0编辑  收藏  举报