给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/perfect-squares
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的思路:从1开始对1到n每个数建立 数->组成该数所需要的最小的完全平方数个数,比如 1->1,2->2, 3-> 3, 4->1...建立一个新的数的映射时需要用到之前的数据,具体方法为:
建立空数组square_list = []
i从1遍历到n。
如果i为完全平方数,在数组中添加1;
否则,初始化count = i,遍历数组中的1到int(i / 2)的元素,计算square_list[j] + square_list[i - j],如果该值小于count,则更新count为该值。
返回square_list[n]。
成绩为:
执行用时 :3636 ms, 在所有 Python 提交中击败了61.86%的用户
内存消耗 :12.1 MB, 在所有 Python 提交中击败了20.28%的用户
代码为:
def sqrt(n):
i = 0
while(i*i < n):
i += 1
return i
def isSquare(n):
if sqrt(n) ** 2 == n:
return True
else:
return False
square_list = []
for i in range(10000):
if i == 0:
square_list.append(0)
elif isSquare(i):
square_list.append(1)
else:
count = i
for j in range(1, int(i/2)+1):
if square_list[j] + square_list[i - j] < count:
count = square_list[j] + square_list[i - j]
square_list.append(count)
class Solution(object):
def sqrt(self, n):
i = 0
while(i*i < n):
i += 1
return i
def isSquare(self, n):
if self.sqrt(n) ** 2 == n:
return True
else:
return False
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
"""
square_list = []
for i in range(n+1):
if i == 0:
square_list.append(0)
elif self.isSquare(i):
square_list.append(1)
else:
count = i
for j in range(1, int(i/2)+1):
if square_list[j] + square_list[i - j] < count:
count = square_list[j] + square_list[i - j]
square_list.append(count)
return square_list[-1]
"""
return square_list[n]