题解 | #汉诺塔问题#
汉诺塔问题
http://www.nowcoder.com/practice/7d6cab7d435048c4b05251bf44e9f185
class Solution { ArrayList<String> res = new ArrayList<>(); public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) { int n = A.size(); move(n,A,B,C); } public void move(int n,List<Integer> A, List<Integer> B, List<Integer> C){ if(n == 1){ // 将A上的取下来放到C上最上面 C.add(0,A.remove(0)); return; } move(n-1,A,C,B); C.add(0,A.remove(0)); move(n-1,B,A,C); } }
import java.util.*; public class Solution { ArrayList<String> res = new ArrayList<>(); public ArrayList<String> getSolution(int n) { // write code here move(n,"left","mid","right"); return res; } public void move(int n,String left,String mid, String right){ if(n == 1){ // 将left上的移到right上 res.add("move from " + left + " to "+right); return; } move(n-1,left,right,mid); res.add("move from " + left + " to "+right); move(n-1,mid,left,right); } }