寻找多种排列字母的方法,使每个前缀和后缀的 B 比 Python 中的 As 多
假设我们有一个包含n个A和2n个B的字符串。我们必须找到可能的排列数量,使得在每个前缀和每个后缀中B的数量大于或等于A的数量
所以,如果输入像n=2,那么输出将是4,因为有两个A和四个B,所以可能的安排是[BBAABB,BABABB,BBABAB,BABBAB]。
示例
让我们看看以下实现以获得更好的理解-
def solve(n): if n==1: return 1 if n==2: return 4 if n%2 != 0: return solve((n-1)//2)**2 else: return solve(n//2)**2 n = 2 print(solve(n))
输入
2输出结果
4