排列序数

手动实现全排列 Link to heading

这个会超时,只通过了 75%

s = input()
ls = [c for c in s]
ls.sort()
num = 0
used = [False] * len(ls)


def dfs(current_s, depth):
    """
    :param current_s: 当前字符串
    :param depth: 当前深度
    """
    global num
    if depth == len(ls):
        if current_s == s:
            print(num)
        num += 1
        return
    for i in range(len(ls)):
        if used[i]:
            continue
        used[i] = True
        dfs(current_s + ls[i], depth+1)
        used[i] = False


dfs('', 0)

借助 itertools 库 Link to heading

因为itertools库使用C语言底层实现,所以速度更快

from itertools import permutations
s = input()
x = sorted(s)
t = 0
for i in permutations(x):
    t += 1
    if ''.join(list(i)) == s:
        print(t - 1)
        break