Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3be77cc

Browse files
add golang solution 279
1 parent babe6e0 commit 3be77cc

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* @lc app=leetcode.cn id=279 lang=golang
3+
* 动态规划的思路,状态转移方程:dp[n] = min(dp[n-1*1]+1, dp[n-2*2]+1, ..., dp[n-k*k]+1), ( 0< k*k <=n )
4+
*/
5+
func numSquares(n int) int {
6+
if n <= 0 {
7+
return 0
8+
}
9+
dp := make([]int, n+1) // 多申请了一份整形,使代码更容易理解, dp[n] 就是 n 的完全平方数的求解
10+
for i := 1; i <= n; i++ {
11+
dp[i] = i // 初始值 dp[n] 的最大值的解,也是最容易求的解
12+
for j := 0; j*j <= i; j++ {
13+
dp[i] = minInt(dp[i-j*j]+1, dp[i])
14+
}
15+
}
16+
return dp[n]
17+
}
18+
19+
func minInt(x, y int) int {
20+
if x < y {
21+
return x
22+
}
23+
return y
24+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /