# 279. Perfect Squares
Question link is here.
# Question
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.
# Solution
This is obviously a greedy problem.
For 1 to n, we try to find the smallest i that the n can be the sum of exactly i square numbers.
And order to check whether a number is square number, we can use a HashSet to store those number.
# Java
class Solution {
HashSet<Integer> candidates = new HashSet<Integer>();
int res;
public int numSquares(int n) {
for(int i = 1; i* i <= n; i++) {
candidates.add(i*i);
}
int i = 1;
for(i = 1; i <= n; i++) {
if(helper(n, i))
return i;
}
return i;
}
public boolean helper(int n, int level) {
if(level == 1) {
return candidates.contains(n);
}
for(Integer i : candidates) {
if(helper(n - i, level - 1))
return true;
}
return false;
}
}
# Python
class Solution:
def numSquares(self, n: int) -> int:
candidates = set()
for i in range(1, int(n ** 0.5) + 1):
candidates.add(i * i)
def helper(n, level):
if level == 1:
return n in candidates
for num in candidates:
if helper(n - num, level-1):
return True
return False
for i in range(1, n+1):
if helper(n, i):
return i
Time Complexity .