全排列的實現之遞迴版與迭代版

gebeng發表於2024-07-30

一、遞迴版


s = ["1","2","3"]
n = len(s)
def dfs(l):
    if l == n:
        print(*s)
        return
    vis = set()
    for i in range(l,n):
        # 防止重複數字,造成答案重複
        if i == l or s[i] not in vis:
            vis.add(s[i])
            s[l],s[i] = s[i],s[l]
            dfs(l + 1)
            s[l],s[i] = s[i],s[l]
dfs(0)

相關文章