程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python 实现【全排列】(python数组全排列)

hfteth 2025-04-10 22:58:01 技术文章 13 ℃
from math import factorial
from collections import Counter

def count_distinct_permutations(s):
    n = len(s)
    char_counts = Counter(s)
    total = factorial(n)
    for count in char_counts.values():
        total //= factorial(count)
    return total

# 读取输入
s = input().strip()
# 计算并输出结果
print(count_distinct_permutations(s))

方法思路

  1. 统计字符频率:首先统计字符串中每个字符出现的次数。
  2. 计算排列数:排列数的计算公式为总排列数除以各重复字符排列数的乘积。具体来说:
  • 总排列数是字符串长度的阶乘:n!。
  • 对于每个字符出现的次数 count,需要除以 count! 来消除重复排列。


Tags:

最近发表
标签列表