47~541连接更新‘

This commit is contained in:
XuDaHaoRen
2021-08-23 19:45:17 +08:00
parent acf1a54f8d
commit 0a8191b5c3
103 changed files with 491 additions and 669 deletions

View File

@@ -9,7 +9,7 @@
## 279.完全平方数
题目地址:https://leetcode-cn.com/problems/perfect-squares/
[力扣题目链接](https://leetcode-cn.com/problems/perfect-squares/)
给定正整数 n找到若干个完全平方数比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
@@ -36,7 +36,7 @@
**我来把题目翻译一下完全平方数就是物品可以无限件使用凑个正整数n就是背包问凑满这个背包最少有多少物品**
感受出来了没,这么浓厚的完全背包氛围,而且和昨天的题目[动态规划322. 零钱兑换](https://mp.weixin.qq.com/s/dyk-xNilHzNtVdPPLObSeQ)就是一样一样的!
感受出来了没,这么浓厚的完全背包氛围,而且和昨天的题目[动态规划322. 零钱兑换](https://programmercarl.com/0322.零钱兑换.html)就是一样一样的!
动规五部曲分析如下:
@@ -70,7 +70,7 @@ dp[0]表示 和为0的完全平方数的最小数量那么dp[0]一定是0。
如果求排列数就是外层for遍历背包内层for循环遍历物品。
在[动态规划322. 零钱兑换](https://mp.weixin.qq.com/s/dyk-xNilHzNtVdPPLObSeQ)中我们就深入探讨了这个问题,本题也是一样的,是求最小数!
在[动态规划322. 零钱兑换](https://programmercarl.com/0322.零钱兑换.html)中我们就深入探讨了这个问题,本题也是一样的,是求最小数!
**所以本题外层for遍历背包里层for遍历物品还是外层for遍历物品内层for遍历背包都是可以的**
@@ -146,7 +146,7 @@ public:
## 总结
如果大家认真做了昨天的题目[动态规划322. 零钱兑换](https://mp.weixin.qq.com/s/dyk-xNilHzNtVdPPLObSeQ),今天这道就非常简单了,一样的套路一样的味道。
如果大家认真做了昨天的题目[动态规划322. 零钱兑换](https://programmercarl.com/0322.零钱兑换.html),今天这道就非常简单了,一样的套路一样的味道。
但如果没有按照「代码随想录」的题目顺序来做的话,做动态规划或者做背包问题,上来就做这道题,那还是挺难的!
@@ -161,7 +161,6 @@ public:
Java
```Java
class Solution {
// 版本一,先遍历物品, 再遍历背包
public int numSquares(int n) {
int max = Integer.MAX_VALUE;
int[] dp = new int[n + 1];
@@ -171,9 +170,7 @@ class Solution {
}
//当和为0时组合的个数为0
dp[0] = 0;
// 遍历物品
for (int i = 1; i * i <= n; i++) {
// 遍历背包
for (int j = i * i; j <= n; j++) {
if (dp[j - i * i] != max) {
dp[j] = Math.min(dp[j], dp[j - i * i] + 1);
@@ -183,28 +180,6 @@ class Solution {
return dp[n];
}
}
class Solution {
// 版本二, 先遍历背包, 再遍历物品
public int numSquares(int n) {
int max = Integer.MAX_VALUE;
int[] dp = new int[n + 1];
// 初始化
for (int j = 0; j <= n; j++) {
dp[j] = max;
}
// 当和为0时组合的个数为0
dp[0] = 0;
// 遍历背包
for (int j = 1; j <= n; j++) {
// 遍历物品
for (int i = 1; i * i <= j; i++) {
dp[j] = Math.min(dp[j], dp[j - i * i] + 1);
}
}
return dp[n];
}
}
```
Python
@@ -212,7 +187,7 @@ Python
```python3
class Solution:
def numSquares(self, n: int) -> int:
'''版本一,先遍历背包, 再遍历物品'''
'''版本一'''
# 初始化
nums = [i**2 for i in range(1, n + 1) if i**2 <= n]
dp = [10**4]*(n + 1)
@@ -226,7 +201,7 @@ class Solution:
return dp[n]
def numSquares1(self, n: int) -> int:
'''版本二 先遍历物品, 再遍历背包'''
'''版本二'''
# 初始化
nums = [i**2 for i in range(1, n + 1) if i**2 <= n]
dp = [10**4]*(n + 1)
@@ -242,22 +217,6 @@ class Solution:
Python3:
```python
class Solution:
'''版本一,先遍历背包, 再遍历物品'''
def numSquares(self, n: int) -> int:
dp = [n] * (n + 1)
dp[0] = 0
# 遍历背包
for j in range(1, n+1):
for i in range(1, n):
num = i ** 2
if num > j: break
# 遍历物品
if j - num >= 0:
dp[j] = min(dp[j], dp[j - num] + 1)
return dp[n]
class Solution:
'''版本二, 先遍历物品, 再遍历背包'''
def numSquares(self, n: int) -> int:
# 初始化
# 组成和的完全平方数的最多个数就是只用1构成