2021年10月25日 星期一

[LeetCode] 279. Perfect Squares

轉自LeetCode

Given an integer n, return the least number of perfect square numbers that sum to n.

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, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

 

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(參考解法)


沒有留言:

張貼留言