279. Perfect Squares
Difficulty: Medium
Given a positive integer _n_, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to _n_.
For example, given _n_ = 12, return 3 because 12 = 4 + 4 + 4; given _n_ = 13, return 2 because 13 = 4 + 9.
Solution
主要思想还是动态规划
通过观察可以得出,dp[j*j]=1,目的是求dp[n]
观察 dp[13],比13小的平方数有 1,4,9,
那么dp[13]取:
dp[1]+dp[13-1]、 dp[4]+dp[13-4]、dp[9]+dp[13-9]中最小的那一个
因此,只要从dp[1]计算到dp[n]即可。
1 | class Solution { |
然后看到一个最优解法, 数学原理:四平方和定理 https://zh.wikipedia.org/wiki/%E5%9B%9B%E5%B9%B3%E6%96%B9%E5%92%8C%E5%AE%9A%E7%90%86
1 |
|