Skip to content

Commit b591d36

Browse files
committed
Add math solution for leetcode 279.
1 parent 8adba39 commit b591d36

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include<iostream>
2+
#include<cmath>
3+
using namespace std;
4+
5+
/* 解题思路见题解 <https://leetcode-cn.com/problems/perfect-squares/solution/shu-xue-fa-bu-shi-yong-dong-tai-gui-hua-ddm33/> */
6+
class Solution {
7+
public:
8+
int numSquares(int n) {
9+
while (n % 4 == 0)
10+
n /= 4;
11+
12+
if (n % 8 == 7)
13+
return 4; // (path 1)
14+
15+
for (int i = 0; i * i <= n; i++)
16+
{
17+
int r = (int)sqrt(n - i * i);
18+
if (i * i + r * r == n)
19+
{
20+
if (i == 0 || r == 0)
21+
return 1; // (path 2)
22+
23+
return 2; // (path 3)
24+
}
25+
}
26+
27+
return 3; // (path 4)
28+
}
29+
};
30+
31+
// Test
32+
int main()
33+
{
34+
Solution sol;
35+
int k = 12;
36+
int res = sol.numSquares(k);
37+
cout << res << endl;
38+
39+
return 0;
40+
}

0 commit comments

Comments
 (0)