Hanoi问题
Hanoi
典型的递推问题,递推公式:T(n) = T(n-1) * 2 + 1,其中T(1) = 1。
分三步进行:
伪码
Hanoi(A,C,n)
if n == 1 then Move(A,C)
else Hanoi(A,B,n-1)
Move(A,C)
Hanoi(B,C,n-1)
奇怪的汉诺塔
代码
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main(){
int d[15],f[15];//d代表3柱,f代表4柱
d[1] = 1;
for (int i = 2; i <= 12; i ++ )
d[i] = d[i - 1]*2 + 1;
memset(f,0x3f,sizeof f);
f[0] = 0;
for (int i = 1; i <= 12; i ++ )
for (int j = 0; j < i; j ++ )
f[i] = min(f[i],f[j] * 2 + d[i - j]);//移动前j个盘子后,剩下i-j个只能在3个柱子上移动
for (int i = 1; i <= 12; i ++ ) cout<<f[i]<<endl;
return 0;
}