漢諾塔問題
阿新 • • 發佈:2020-09-09
題目地址:https://leetcode-cn.com/problems/hanota-lcci/submissions/
題目描述:
分析:假設我們在A柱子上有8個圓盤需要移動到C柱子上面,那麼利用遞迴思想,我們只需要先將上面的7個圓盤移動到B柱子上,然後將最底下的圓盤移動到C柱子上,再將B柱子上的圓盤移動到C柱子上,此時,A盤已經空著了,就變成了輔助柱子。
編寫程式碼:
public class Hanota_0806 { static class Solution { 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 (1 == n) { C.add(A.get(A.size() - 1)); A.remove(A.size() - 1); return; } else { move(n - 1, A, C, B); C.add(A.get(A.size() - 1)); A.remove(A.size() - 1); move(n - 1, B, A, C); } } } // 測試 public static void main(String[] args) { List<Integer> A = new ArrayList<>(); List<Integer> B = new ArrayList<>(); List<Integer> C = new ArrayList<>(); A.add(2); A.add(1); A.add(0); System.out.println(A); Solution solution = new Solution(); solution.hanota(A, B, C); System.out.println(C); } }