322. 零钱兑换
题目:322. 零钱兑换 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
初始化情况值得思考
条件判断比较复杂
solution
public class Solution {
public int CoinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
dp[0] = 0;
for(int i = 0; i < coins.Length; i ++)
{
for(int j = 1; j <= amount; j ++)
{
if(i == 0)
{
dp[j] = j >= coins[0] ? (dp[j - coins[0]] == -1 ? -1 : dp[j - coins[0]] + 1): -1;
}
else
{
if(j >= coins[i])
{
dp[j] = Math.Min( (dp[j] == -1? int.MaxValue : dp[j]), dp[j - coins[i]] == -1 ? int.MaxValue : dp[j - coins[i]] + 1);
}
if(dp[j] == int.MaxValue) dp[j] = -1;
}
}
//Log first line
if(i == 0)
{
foreach(int number in dp)
{
Console.WriteLine(number);
}
}
}
return dp[amount];
}
}
gpt(可能优化)版
public class Solution {
public int CoinChange(int[] coins, int amount) {
// 创建 dp 数组并初始化
int[] dp = new int[amount + 1];
// 将 dp 数组初始化为一个很大的值
Array.Fill(dp, int.MaxValue);
dp[0] = 0; // 0 元需要 0 个硬币
// 遍历所有的金额
for (int i = 1; i <= amount; i++)
{
// 遍历所有的硬币
foreach (int coin in coins)
{
if (i >= coin && dp[i - coin] != int.MaxValue)
{
dp[i] = Math.Min(dp[i], dp[i - coin] + 1);
}
}
}
// 如果 dp[amount] 仍然是 int.MaxValue,说明无法组成金额
return dp[amount] == int.MaxValue ? -1 : dp[amount];
}
}
summary
不能凑成的情况设为-1,每一次取值都要判断
279. 完全平方数
solution
public class Solution {
public int NumSquares(int n) {
// 创建 dp 数组并初始化
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++)
{
dp[i] = int.MaxValue; // 初始化为一个大的值
// 尝试所有可能的完全平方数
for (int j = 1; j * j <= i; j++)
{
dp[i] = Math.Min(dp[i], dp[i - j * j] + 1);
}
}
return dp[n];
}
}
summary
139. 单词拆分
题目:139. 单词拆分 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
好巧秒的转化。。。这谁能想到啊,唉
solution
public class Solution {
public bool WordBreak(string s, IList<string> wordDict) {
HashSet<string> wordSet = new HashSet<string>(wordDict);
int n = s.Length;
bool[] dp = new bool[n + 1];
dp[0] = true;
for(int i = 1; i < n + 1; i ++)
{
for(int j = 0; j < i; j ++)
{
if(dp[j] && wordSet.Contains(s.Substring(j, i - j)))
{
dp[i] = true;
break;
}
}
}
return dp[n];
}
}
summary
dp:
1、dp[ i ]:字符串s的前‘i’个字符是否可以被拆分成字典中的单词
2、dp[ 0 ] = true,空字符串拆分为空单词
3、递推:
对每个位置 i 遍历所有可能的结束位置 j,若dp[ j ]为true,且字符串从 j 到 i 的子串再字典中,则dp[ i ]为true