forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0279.cpp
More file actions
65 lines (46 loc) · 1.29 KB
/
0279.cpp
File metadata and controls
65 lines (46 loc) · 1.29 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
//Lagrange's 4 square theorem solution
//Fastest possible solution
class Solution {
public:
int sq_check(int num){
int sq_rt = (int)sqrt(num);
if(sq_rt * sq_rt == num)
return 1;
else
return 0;
}
int numSquares(int n) {
//if n is perfect square
if(sq_check(n))
return 1;
int count = 0;
//check whether n satisfies 4^a (8k + 7) equation
//obtain (8k + 7) value
while(!(n % 4))
n /= 4;
//if n is of the form 4^a (8k + 7), 4 squares exist
if(n % 8 == 7)
return 4;
//if n is sum of 2 squares
for(int i = 1; i*i <= n; i++)
if(sq_check(n - i*i))
return 2;
//otherwise
return 3;
}
};
//DP solution
class Solution {
public:
int numSquares(int n) {
int dp[10001] = {0};
for(int i = 1; i <= n; i++){
int min_val = INT_MAX;
for(int j = 1; j*j <= i; j++){
min_val = min(min_val, dp[i - (j*j)]);
dp[i] = 1 + min_val;
}
}
return dp[n];
}
};