-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode279DPperfectsquares.cpp
73 lines (68 loc) · 1.58 KB
/
leetcode279DPperfectsquares.cpp
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
//https://leetcode.com/problems/perfect-squares/
//2d arraysoln
class Solution {
public:
int numSquares(int n) {
if(n<=3){
return n;
}
int x=sqrt(n);
x++;
// int dp[x+1];
//vector<int > dp(n+1, INT_MAX-1);
// vector<int > dp1(n+1,0);
int *dp=new int[n+1];
int *dp1=new int[n+1];
// int dp1[x+1];
for(int j=0;j<n+1;j++){
// dp.push_back(INT_MAX-1);
//dp1.push_back(0);
dp[j]=INT_MAX-1;
dp1[j]=0;
}
dp[0]=0;
for(int i=1;i<x+1;i++){
for(int j=1;j<n+1;j++){
if(i*i<=j){
dp1[j]=min(1+dp1[j-(i*i)],dp[j]);
}
else{
dp1[j]=dp[j];
}
}
dp=dp1;
}
return dp1[n];
}
};
//space optimized soln
class Solution {
public:
int numSquares(int n) {
if(n<=3){
return n;
}
int x=sqrt(n);
x++;
// int dp[x+1];
vector<int > dp,dp1;
// int dp1[x+1];
for(int j=0;j<n+1;j++){
dp.push_back(INT_MAX-1);
dp1.push_back(0);
}
dp[0]=0;
for(int i=1;i<x+1;i++){
for(int j=1;j<n+1;j++){
if(i*i<=j){
dp1[j]=min(1+dp1[j-(i*i)],dp[j]);
}
else{
dp1[j]=dp[j];
}
}
dp=dp1;
}
return dp1[n];
}
};