Given an integer
A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example,
Example 1:
Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13 Output: 2 Explanation: 13 = 4 + 9.
Constraints:
1 <= n <= 104
Solution
這題最快的解釋用數學公式,但這邊就不討論,因為平常也不會背數學公式
這次採用DP的方式來解,有點像是套用 prefixSum 的概念
dp[n] = min(dp[n], dp[n - j*j]) = min(當下的值,從上一個 perfect squares 再加 1 )
可以想成 n = a + perfect square-> a = n - perfect square
也就是從 a 要變成 n,需要再一個 perfect square
這題的思路也像這題 322. Coin Change
kotlin(參考解法)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun numSquares(n: Int): Int { | |
val dp = IntArray(n+1){Int.MAX_VALUE} | |
dp[0] = 0 | |
for(i in 1..n) { | |
var j = 1 | |
while(j*j <= i) { | |
dp[i] = Math.min(dp[i], dp[i-j*j]+1) | |
++j | |
} | |
} | |
return dp[n] | |
} | |
} |
沒有留言:
張貼留言