python - 这个程序的空间复杂度真的是 O(1) 吗?
问题描述
我今天遇到了奇怪的信息。我会说这段代码的空间复杂度是 O(N)。每次递归发生时,都会创建一个新的堆栈帧。并且递归调用的数量与矩阵的大小成正比(在本例中为 4)。我是对的还是我什么都没看到?
顺便说一句,这里的问题是找到名人(每个人都认识他们,但他们不认识任何人)。我们有矩阵所需的信息,1 表示知道,0 表示不知道。例如,人 0 不认识人 1,但认识人 2。
# Person with 2 is celebrity
MATRIX = [[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]]
def knows(a, b):
return MATRIX[a][b]
# Returns -1 if a potential celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
def findPotentialCelebrity(n):
# Base case
if (n == 0):
return 0;
# Find the celebrity with n-1
# persons
id_ = findPotentialCelebrity(n - 1)
# If there are no celebrities
if (id_ == -1):
return n - 1
# if the id knows the nth person
# then the id cannot be a celebrity, but nth person
# could be on
elif knows(id_, n - 1):
return n - 1
# if the id knows the nth person
# then the id cannot be a celebrity, but nth person
# could be one
elif knows(n - 1, id_):
return id_
# If there is no celebrity
return - 1
# Returns -1 if celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
# a wrapper over findCelebrity
def Celebrity(n):
# Find the celebrity
id_=findPotentialCelebrity(n)
# Check if the celebrity found
# is really the celebrity
if (id_ == -1):
return id_
else:
c1=0
c2=0
# Check the id is really the
# celebrity
for i in range(n):
if (i != id_):
c1 += knows(id_, i)
c2 += knows(i, id_)
# If the person is known to
# everyone.
if (c1 == 0 and c2 == n - 1):
return id_
return -1
# Driver code
if __name__ == '__main__':
n=4
id_=Celebrity(n)
if id_ == -1:
print("No celebrity")
else:
print("Celebrity ID", id_)
解决方案
推荐阅读
- here-api - 无法从英语更改语言
- c# - 在 XmlDocument 中的第一个节点中更改大小写
- sql - 我想使用 SELECT 语句中其他列的值来更新空列的值
- python - 如何计算单词及其相关组?
- java - 使用 Jackson 解析深度嵌套的 JSON 属性
- python - 如何获得预测值和测试数据,并可视化实际与预测?
- python - ValueError:无法将输入数组从形状(3591)广播到形状(3600)
- android - 如何通过点击菜单中的选项来隐藏地图图钉?
- google-sheets - 删除源数据后的 Google 表格剩余公式值
- linux - 创建一个平面 tar 文件,其中包含以“a”开头的目录中的每个文件名