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的平方数的最少个数。
leastNumOfSquare[i]表示和为i的平方数的最少个数,因此leastNumOfSquare[n]即为所求。i可以由某一个数加上一个平方数所得,因此要使leastNumOfSquare[i]最小,就要找到一个平方数,使得leastNumOfSquare[i - 该平方数]最小,所以状态转移方程为leastNumOfSquare[i] = min(leastNumOfSquare[i], leastNumOfSquare[i - j * j] + 1)
源代码
1 | class Solution { |