[LeetCode] Perfect Squares

279. Perfect Squares

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
int dp[10001];
int dfs(int n) {
if(dp[n] != -1) return dp[n];
dp[n] = INT_MAX;
for(int i = 1; i*i <= n; i++) {
dp[n] = min(dfs(i * i) + dfs(n - i*i), dp[n]);
}
return dp[n];
}
public:
int numSquares(int n) {
memset(dp, -1, sizeof(dp));
dp[0] = 0;
for(int i = 1; i*i <= n; i++) dp[i*i] = 1;
return dfs(n);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/perfect-squares/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.