Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
cracking-the-safe.py 1.79 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-13 01:56 +08:00 . add complexity
# Time: O(k^n)
# Space: O(k^n)
class Solution(object):
def crackSafe(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
M = k**(n-1)
P = [q*k+i for i in xrange(k) for q in xrange(M)] # rotate: i*k^(n-1) + q => q*k + i
result = [str(k-1)]*(n-1)
for i in xrange(k**n):
j = i
# concatenation in lexicographic order of Lyndon words
while P[j] >= 0:
result.append(str(j//M))
P[j], j = -1, P[j]
return "".join(result)
# Time: O(n * k^n)
# Space: O(n * k^n)
class Solution2(object):
def crackSafe(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
result = [str(k-1)]*n
lookup = {"".join(result)}
total = k**n
while len(lookup) < total:
node = result[len(result)-n+1:]
for i in xrange(k):
neighbor = "".join(node) + str(i)
if neighbor not in lookup:
lookup.add(neighbor)
result.append(str(i))
break
return "".join(result)
# Time: O(n * k^n)
# Space: O(n * k^n)
class Solution3(object):
def crackSafe(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
def dfs(k, node, lookup, result):
for i in xrange(k):
neighbor = node + str(i)
if neighbor not in lookup:
lookup.add(neighbor)
result.append(str(i))
dfs(k, neighbor[1:], lookup, result)
break
result = [str(k-1)]*(n-1)
lookup = set()
dfs(k, "".join(result), lookup, result)
return "".join(result)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助