题解 | #汉诺塔问题#
汉诺塔问题
https://www.nowcoder.com/practice/7d6cab7d435048c4b05251bf44e9f185
import java.util.*; public class Solution { static ArrayList<String> list=new ArrayList<String>();//存放结果 public ArrayList<String> getSolution(int n) { // write code here hannuo(n,"left","right","mid");//递归汉诺函数 return list; } public void hannuo(int n,String a,String b,String c){//a,表示左,b表示右,c表示中 if(n==1){ list.add(String.format("move from %s to %s",a,b));//n为1时,直接从左边挪到右边 }else{ hannuo(n-1,a,c,b);//先将n-1层挪到中间 hannuo(1,a,b,c);//再将右边剩余的1层直接挪到右边 hannuo(n-1,c,b,a);//最后将中间n-1层挪到右边 } } }