递归问题中的汉诺塔问题:
public static void hanoi(int n){ if (n>0){ func(n,"left","mid","right"); } } public static void func(int n,String from,String mid,String to){ if (n==1)System.out.println("move from"+from+"to"+to); else{ func(n-1,from,to,mid);//将n-1个元素,通过to,从from移动到mid func(1,from,mid,to);//将最底下的元素通过mid,从from移动到to。 func(n-1,mid,from,to);//将n-1个元素,通过from,从mid,移动到to。 } }
其中,n代表需要移动的元素的个数。
是严蔚敏老师的数据结构课本上的一个案例。用于理解递归的过程是很有效的。