-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path279.cpp
More file actions
48 lines (46 loc) · 1.09 KB
/
Copy path279.cpp
File metadata and controls
48 lines (46 loc) · 1.09 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
class Solution {
public:
int numSquares(int n) {//O(nsqrt(n))
if(n<4)
return n;
vector<int> dp(n+1);
dp[0] = 0;
dp[1] = 1;
for(int i=2; i<=n; i++){
dp[i] = i;
for(int j=1; j*j<=i; j++){
dp[i] = min(dp[i],1+dp[i-(j*j)]);
}
}
return dp[n];
}
};
class Solution {
public:
int numSquares(int n) {
queue<int> q;
unordered_set<int> visited;
int res = 0;
q.push(0);
visited.insert(0);
while(!q.empty()){
int size = q.size();
res++;
while(size--){
int u = q.front();q.pop();
for(int i=1; i*i<=n; i++){
int v = u + i*i;
if(v==n)
return res;
if(v>n)
break;
if(!visited.count(v)){
visited.insert(v);
q.push(v);
}
}
}
}
return res;
}
};