设m.n均为自然数,m可表示为一些不超过n的自然数之和,f(m,n)为这种表示方式的数目。
例f(5,3)=5,有5种表示方式:3+2,3+1+1,2+2+1,2+1+1+1,1+1+1+1+1。递归算法求f(m,n).
f(m, n)
可以对照图表,不难观察出来,总共有这样几种情况了
(1). m < n
f(1, 2) = f(1, 3) = f(1, 4) = ... = f(1, 1)
f(2, 3) = f(2, 4) = f(2, 5) = ... = f(2, 2)
......
得出结论:
m < n : f(m, n) = f(m, m)
/*====================================================*/
(2). n = 1
f(1, 1) = f(2, 1) = f(3, 1) = ... = 1
得出结论:
n = 1 : f(m, n) = 1;
/*====================================================*/
(3). m = n
f(2, 2) = 2 = 1+1 = 1+f(2, 1)
f(3, 3) = 3 = 1+2 = 1+f(3, 2)
f(4, 4) = 4 = 1+3 = 1+f(4, 3)
......
m = n : f(m, n) = 1+f(m, m-1)
/*====================================================*/
(4). m > n
m-n = 1
f(3, 2) = 2 = f(3, 1) + 1 = 1+1
f(4, 3) = 4 = f(4, 2) + 1 = 3+1
f(5, 4) = 6 = f(5, 3) + 1 = 5+1
......
而f(m, n) = 1的只有f(m, 1),所以我们可以用f(1, 1)统一代替
于是有了,当m-n=1时
f(m, n) = f(m, n-1) + f(1, 1)
---------------------------
m-n = 2
f(4, 2) = 3 = f(4, 1) + 2 = 1+2
f(5, 3) = 5 = f(5, 2) + 2 = 3+2
f(6, 4) = 9 = f(6, 3) + 2 = 7+2
......
而f(m, n) = 2的只有f(2, 2)与f(3,2)
于是有了,当m-n = 2时
f(m, n) = f(m, n-1) + f(2, 2)
f(m, n) = f(m, n-1) + f(3, 2)
---------------------------
m-n = 3
f(5, 2) = 3 = f(5, 1) + 2 = 1+2
f(6, 3) = 7 = f(6, 2) + 3 = 4+3
f(7, 4) = 11 = f(7, 3) + 3 = 8+3
......
而f(m, n) = 2的有f(3, 2), f(2, 2)
而f(m, n) = 3的有f(3, 3), f(4, 2), f(5, 2)
于是有了,当m-n = 3时
m = 5时
f(m, n) = f(m, n-1) + f(3, 2) // ?
f(m, n) = f(m, n-1) + f(2, 2) // f((5-2),(5-2))
------------------
m > 5时
f(m, n) = f(m, n-1) + f(3, 3) // f((6-3),(6-3)) or f((7-4),(7-4))
f(m, n) = f(m, n-1) + f(4, 2) // ?
f(m, n) = f(m, n-1) + f(5, 2) // ?
------------------
所以可以推出来
当m > n时
f(m, n) = f(m, n-1) + f(m-n, m-n))
不过别忘记了,我们之前有对m=n的情况下,把所有的值增加1了,然后才去运算的。
所以我们还要针对m=n的做减1的动作。
if (m == n)
{
nRet--;
}
附上代码: