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.
难度: medium
题目:给定一正整数 n,找出其最少个平方数之和为 n。
思路:参考 (322. Coin Change)
Runtime: 22 ms, faster than 91.72% of Java online submissions for Perfect Squares.Memory Usage: 36.6 MB, less than 47.46% of Java online submissions for Perfect Squares.
class Solution {
public int numSquares(int n) {
int s = (int) Math.floor(Math.sqrt(n));
if (s * s == n) {
return 1;
}
int[] squares = new int[s];
int[] nums = new int[n + 1];
for (int i = 1; i <= s; i++) {
squares[i – 1] = i * i;
if (squares[i – 1] < nums.length) {
nums[squares[i – 1]] = 1;
}
}
for (int i = squares[0]; i <= n; i++) {
if (nums[i] > 0) {
continue;
}
nums[i] = n + 1;
for (int j = 0; j < squares.length && i – squares[j] >= 0; j++) {
if (nums[i – squares[j]] > 0) {
nums[i] = Math.min(nums[i – squares[j]] + 1, nums[i]);
}
}
}
return nums[n];
}
}