# Leetcode 279:完全平方数（最详细解决方案！！！）

输入: n = 12



输入: n = 13



12 = 9 + 1 + 1 + 1


q : (4, 1) (1, 1)


q : (1, 1) (3, 2)


class Solution:
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
q = list()
q.append([n, 0])
visited = [False for _ in range(n+1)]
visited[n] = True

while any(q):
num, step = q.pop(0)

i = 1
tNum = num - i**2
while tNum >= 0:
if tNum == 0:
return step + 1

if not visited[tNum]:
q.append((tNum, step + 1))
visited[tNum] = True

i += 1
tNum = num - i**2


Lagrange 四平方定理： 任何一个正整数都可以表示成不超过四个整数的平方之和。

if and only if n is not of the form $n = 4^a(8b + 7)$ for integers a and b.

class Solution:
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
while n % 4 == 0:
n /= 4

if n % 8 == 7:
return 4

a = 0
while a**2 <= n:
b = int((n - a**2)**0.5)
if a**2 + b**2 == n:
return (not not a) + (not not b)

a += 1

return 3


num[n] = min(num[n], num[n-i**2] + 1)


class Solution:
_dp = list()
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
dp = self._dp
dp = [float('inf') for i in range(n + 1)]
dp[0] = 0
for i in range(n + 1):
j = 1
while i + j**2 <= n:
dp[i + j**2] = min(dp[i + j**2], dp[i] + 1)
j += 1

return dp[n]


class Solution:
_dp = [0]
def numSquares(self, n):
dp = self._dp
while len(dp) <= n:
dp += list((min(dp[-i*i] for i in range(1, int(len(dp)**0.5+1))) + 1,))
return dp[n]


03-06 2413

06-07 487

09-08 4540

10-11 370

10-24 140

06-25 3180

03-13 242

11-19 11

05-24 4966

06-12 1381

10-30 850

08-07 8418

10-18 1175

10-10 3万+

10-12 650

10-11 2737

01-09 1497

01-11 950

05-09 173

04-11 157

10-08 5万+

03-04 569

10-11 6万+

10-22 35万+

02-14 1956

01-16 442

01-28 55

02-16 44

03-18 28

04-10 290

09-20 11万+

12-13 87

09-10 3320

03-26 292

02-18 106

07-23 32

09-17 417

01-18 596

06-25 207

04-06 183

04-28 571

04-23 1222

10-16 26

11-26 483

12-30 45

01-22 1090

07-15 37

11-25 650

12-24 1611

06-14 237

04-13 28

05-28 617

10-02 103

08-10 713

01-06 154

12-05 440

09-23 1720

05-12 253

09-25 45

06-04 9799

10-30 212

03-10 246

01-26 301

04-23 373

03-06 198

03-14 859

09-18 3341

09-25 990

11-02 882

04-13 1246

08-27 1271

07-14 193

08-27 55

10-29 177

11-29 2296

04-05 265

04-14 1979

06-08 338

#### 从 LeetCode 279 实践动态规划

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客