forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay-27-Perfect Squares.cpp
More file actions
63 lines (41 loc) · 896 Bytes
/
Day-27-Perfect Squares.cpp
File metadata and controls
63 lines (41 loc) · 896 Bytes
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
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
class Solution {
public:
int numSquares(int n) {
if(n<=3) return n;
int dp[n+1];
for(int i=0;i<=n;i++){
dp[i]=i;
for(int j=1;j*j<=i;j++){
int sq=j*j;
dp[i]=min(dp[i], 1+dp[i-sq]);
}
}
return dp[n];
}
};
//Recursion
class Solution {
int solve(int n)
{
if(n<=3)
return n;
int ans=n;
for(int i=1;i*i<=n;++i)
ans = min(ans,1+solve(n-i*i));
return ans;
}
public:
int numSquares(int n) {
int ans = solve(n);
return ans;
}
};