[DP解题] 完美平方数
原题链接:https://leetcode.com/problems/perfect-squares/
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
题目大意是:给定一个正整数n,找到最少的平方数之和等于n。
例如:给定n=12,而 12=4+4+4,4是2的平方。
输出结果为:3
例如:给定n=13,而 13 = 4+9,4是2的平方,9是3的平方;而 13 = 4+9.
算法分析
用dp[n]表示给定的n的完美平方数,那么
dp[0] = 0
dp[1] = dp[0]+1 = 1
dp[2] = dp[1]+1 = 2
dp[3] = dp[2]+1 = 3
dp[4] = Min{ dp[