Given a positive integer n, find the least number of perfect square numbers (for example,
1, 4, 9, 16, ...
) which sum to n.
For example, given n =
12
, return 3
because 12 = 4 + 4 + 4
; given n = 13
, return 2
because 13 = 4 + 9
.
Solutions:
Using DP. For many detailed explanation please refer to: https://leetcode.com/discuss/58056/summary-of-different-solutions-bfs-static-and-mathematics
One of trick to use is so called "Static DP", which use a static vector to save already computed results among huge number of test cases to same more time. But for single call, it is no difference to what I present here.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int numSquares(int n) { | |
if(n<=0) return 0; | |
vector<int> M(n+1, INT_MAX); | |
M[0]=0; | |
for(int i=1; i<=n; i++) | |
for(int j=1; j*j<=i; j++) | |
M[i]=min(M[i], M[i-j*j]+1); | |
return M.back(); | |
} | |
}; |
Round 3:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int numSquares(int n) { | |
vector<int> myT(n+1, INT_MAX); | |
myT[0]=0; | |
for(int i=1; i<=n; i++){ | |
for(int j=1; j*j<=i; j++) | |
myT[i] = min(myT[i], myT[i-j*j]+1); | |
} | |
return myT.back(); | |
} | |
}; |
No comments:
Post a Comment