代码随想录刷题第44天
零钱兑换 II
/*
* @lc app=leetcode.cn id=518 lang=cpp
*
* [518] 零钱兑换 II
*
* https://leetcode.cn/problems/coin-change-ii/description/
*
* algorithms
* Medium (70.06%)
* Likes: 1006
* Dislikes: 0
* Total Accepted: 219.3K
* Total Submissions: 312.8K
* Testcase Example: '5\n[1,2,5]'
*
* 给你一个整数数组 coins 表示不同面额的硬币,另给一个整数 amount 表示总金额。
*
* 请你计算并返回可以凑成总金额的硬币组合数。如果任何硬币组合都无法凑出总金额,返回 0 。
*
* 假设每一种面额的硬币有无限个。
*
* 题目数据保证结果符合 32 位带符号整数。
*
*
*
*
*
*
* 示例 1:
*
*
* 输入:amount = 5, coins = [1, 2, 5]
* 输出:4
* 解释:有四种方式可以凑成总金额:
* 5=5
* 5=2+2+1
* 5=2+1+1+1
* 5=1+1+1+1+1
*
*
* 示例 2:
*
*
* 输入:amount = 3, coins = [2]
* 输出:0
* 解释:只用面额 2 的硬币不能凑成总金额 3 。
*
*
* 示例 3:
*
*
* 输入:amount = 10, coins = [10]
* 输出:1
*
*
*
*
* 提示:
*
*
* 1
* 1
* coins 中的所有值 互不相同
* 0
*
*
*/
// @lc code=start
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int change(int amount, vector<int>& coins) {
int result ;
vector<int> dp(amount+1,0);
dp[0] = 1;
for (int i = 0; i < coins.size(); i++)
{
for (int j = 0; j <= amount; j++)
{
if (j >= coins[i])
{
dp[j] += dp[j-coins[i]];
}
}
}
result = dp[amount];
return result;
}
};
// @lc code=end
组合总和 Ⅳ
/*
* @lc app=leetcode.cn id=377 lang=cpp
*
* [377] 组合总和 Ⅳ
*
* https://leetcode.cn/problems/combination-sum-iv/description/
*
* algorithms
* Medium (53.15%)
* Likes: 755
* Dislikes: 0
* Total Accepted: 129K
* Total Submissions: 242.8K
* Testcase Example: '[1,2,3]\n4'
*
* 给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。
*
* 题目数据保证答案符合 32 位整数范围。
*
*
*
* 示例 1:
*
*
* 输入:nums = [1,2,3], target = 4
* 输出:7
* 解释:
* 所有可能的组合为:
* (1, 1, 1, 1)
* (1, 1, 2)
* (1, 2, 1)
* (1, 3)
* (2, 1, 1)
* (2, 2)
* (3, 1)
* 请注意,顺序不同的序列被视作不同的组合。
*
*
* 示例 2:
*
*
* 输入:nums = [9], target = 3
* 输出:0
*
*
*
*
* 提示:
*
*
* 1
* 1
* nums 中的所有元素 互不相同
* 1
*
*
*
*
* 进阶:如果给定的数组中含有负数会发生什么?问题会产生何种变化?如果允许负数出现,需要向题目中添加哪些限制条件?
*
*/
// @lc code=start
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<long> dp(target+1,0);
dp[0] = 1;
for (int i = 0; i <= target; i++)
{
for (int j = 0; j < nums.size(); j++)
{
if (i >= nums[j]&& dp[i] < INT_MAX - dp[i - nums[j]])
{
dp[i] += dp[i-nums[j]];
}
}
}
int result = (int)dp[target];
return result;
}
};
// @lc code=end