leetcode 279. 完全平方数

题解

动态规划,dp[i] = min(dp[i], dp[j]+dp[i-j]),如果i为完全平方数, 则预先设置dp[i]=1

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func numSquares(n int) int {
dp := make([]int, n+1)
for i, j := 1, 1; i <= n; {
dp[i] = 1
j++
i = j * j
}
for i := 1; i <= n; i++ {
if dp[i] != 1 {
dp[i] = dp[1] + dp[i-1]
}
for j := 1; j <= i/2; j++ {
if dp[i] > dp[j]+dp[i-j] {
dp[i] = dp[j]+dp[i-j]
}
}
}
return dp[n]
}