mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
添加0279.完全平方数java版本二解法
This commit is contained in:
@ -161,6 +161,7 @@ public:
|
||||
Java:
|
||||
```Java
|
||||
class Solution {
|
||||
// 版本一,先遍历物品, 再遍历背包
|
||||
public int numSquares(int n) {
|
||||
int max = Integer.MAX_VALUE;
|
||||
int[] dp = new int[n + 1];
|
||||
@ -170,7 +171,9 @@ 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);
|
||||
@ -180,6 +183,28 @@ 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:
|
||||
@ -187,7 +212,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)
|
||||
|
Reference in New Issue
Block a user