zoukankan      html  css  js  c++  java
  • 汉诺塔问题

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

  • 相关阅读:
    双击返回 退出程序
    读取InputStream 中的内容
    wsgi服务器
    python 中的GIL
    json
    __getattr__
    错误类型
    __slot__用法
    获取属性以及基本方法
    linux IO
  • 原文地址:https://www.cnblogs.com/fanlumaster/p/13637844.html
Copyright © 2011-2022 走看看