涂色问题(Python)
题目:将一个圆形等分成N个小扇形,将这些扇形标记为1,2,3,…,N。现在使用M种颜色对每个扇形进行涂色,每个扇形涂一种颜色,且相邻的扇形颜色不同,问有多少种不同的涂法?(N≥1,M≥3)
参考:https://blog.csdn.net/THmen/article/details/79529355
递归解决:
当n=1是,f(1,m) = m
当n=2是,f(1,m) = m(m-1)
当n=3是,f(1,m) = m(m-1)(m-2)
当n=4时,f(4,m) = m(m-1)(m-2)(m-2) + m(m-1)(m-1) = m(m-1)(m^2-3m+3)
当n=5时,f(5,m) = m(m-1)(m-2)(m-2) + m(m-1)(m-1)(m-1)= m(m-1)(m^2-3m+3)(m-1)= f(4,m)(m-1)
可推出关系 f(n,m) = f(n-1,m)(m-1)
def calculate(n,m):
"""
:param n: n个扇形
:param m: m种颜色
:return: 涂法的种类
"""
if n == 1:
return m
if n == 2:
return m * (m-1)
if n == 3:
return m * (m-1) * (m-2)
if n == 4:
return m * (m-1) * (m-2) * (m-2) + m * (m-1) * (m-1)
return calculate(n-1,m) * (m-1)
print(calculate(4,4))