Re: [问题] 1-9位数不重复印出来 (Python)

楼主: penguin7272 (企鹅)   2016-12-03 00:15:30
认真做 dfs, 结果是照字典序排
这个比较快的版本是直接改状态
benchmark N = 8, 前篇 python3 用 len(set(x)) = len(x) 要 100 秒
这份大概五秒 XD
#!/usr/bin/env python3
import sys
def solve(N):
used = [False] * 10
strs = []
def dfs():
yield ''.join(strs)
if len(strs) == N:
return
for i in range(10):
if not used[i]:
strs.append(str(i))
used[i] = True
yield from dfs()
strs.pop()
used[i] = False
for i in range(1, 10):
used[i] = True
strs.append(str(i))
yield from dfs()
used[i] = False
strs.pop()
power = int(sys.argv[1])
print(', '.join(solve(power)))

Links booklink

Contact Us: admin [ a t ] ucptt.com