汉诺塔问题

题目地址: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);
    }
}

原文地址:https://www.cnblogs.com/fanlumaster/p/13637844.html