我看了LeetCode上的问题270. 完全平方数:
我使用以下算法解决了这个问题:Given an integer n, return the least number of perfect square numbers that sum to n.
A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.>
Example 1:
Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4.
def numSquares(n):
squares = [i**2 for i in range(1, int(n**0.5)+1)]
step = 1
queue = {n}
while queue:
tempQueue = set()
for node in queue:
for square in squares:
if node-square == 0:
return step
if node < square:
break
tempQueue.add(node-square)
queue = tempQueue
step += 1
问题
这个算法的时间复杂度是多少?每一层的分支次数为 sqrt(n),但是有些分支注定会早早结束... 这让我想知道如何推导时间复杂度。
该算法基本上通过减去每个可能的数字来从目标数到0,这些数字包括:[1、4、9、sqrt(n) 等],然后对获取的每个数字执行同样的操作。