-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path279.cpp
More file actions
82 lines (78 loc) · 1.46 KB
/
279.cpp
File metadata and controls
82 lines (78 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
// dfs + cache
class Solution {
public:
int numSquares(int n) {
cache = vector<int>(n + 1, -2);
return dfs(n);
}
private:
int dfs(int n) {
if (n < 0) {
return -1;
}
if (n == 0) {
return 0;
}
if (cache[n] != -2) {
return cache[n];
}
int ret = n + 1;
int y;
for (int i = 1; i*i <= n; ++i) {
y = dfs(n - i * i);
if (y == -1) {
continue;
}
ret = min(ret, y + 1);
}
cache[n] = ret;
return ret;
}
private:
vector<int> cache;
};
/*
dfs(12)
[...,3,...]
dfs(8)
[...,2,...]
dfs(4)
[2,1]
dfs(1) dfs(0)
[1] [0]
*/
// dp
// bottom up
class SolutionV2 {
public:
int numSquares(int n) {
vector<int> dp(n + 1, n + 1);
dp[0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= i; ++j) {
if (i - j * j >= 0) {
dp[i] = min(dp[i], dp[i - j * j] + 1);
}
}
}
return dp[n];
}
};
int main()
{
{
Solution s;
int ret = s.numSquares(12);
assert(ret == 3);
}
{
SolutionV2 s;
int ret = s.numSquares(12);
assert(ret == 3);
}
return 0;
}