-
Notifications
You must be signed in to change notification settings - Fork 1
/
NumSquares.cs
62 lines (60 loc) · 1.51 KB
/
NumSquares.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Async
{
public class NumSquaresClass
{
/// <summary>
/// 动态规划实现
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
public int NumSquares(int n)
{
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++)
{
dp[i] = n;
}
for (int i = 1; i <= n; i++)
{
int j = 1;
while (i - j * j >= 0)
{
dp[i] = Math.Min(dp[i], dp[i - j * j] + 1);
j++;
}
}
return dp[n];
}
/// <summary>
/// 四平方和定理实现
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
public int NumSquares2(int n)
{
while (n % 4 == 0)
{
n /= 4;
}
if (n % 8 == 7)
{
return 4;
}
for (int i = 0; i * i <= n; i++)
{
int r = (int)Math.Sqrt(n - i * i);
if (i * i + r * r == n)
{
if (i == 0 || r == 0) return 1;
return 2;
}
}
return 3;
}
}
}