首页 > 其他 > 详细

(递归) 汉诺塔问题 lintcode 169

时间:2019-09-07 19:55:21      阅读:99      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 技术分享图片

 

 技术分享图片

 

将n个从小到大的(上到下)盘子从A移动到C,借助B。其中大的盘子不能放在小的盘子上面输出模拟过程。

将n个盘子从A移动到C => 将n-1个盘子从A移动到B , 再将最底部的一个盘子从A移动到C,最后将B上的n-1个盘子从B移动到C

class Solution {
public:
    /**
     * @param n: the number of disks
     * @return: the order of moves
     */
    vector<string> res;
    vector<string> towerOfHanoi(int n) {
        // write your code here
        move(n, "A", "B", "C");
        return res;
    }
    void move(int n, string from, string buffer, string to){
        if(n==1){
            string s = "from "+ from + " to " + to ;
            res.push_back(s);
        }
            
        else{
            move(n-1, from, to, buffer);
            move(1, from, buffer, to);
            move(n-1, buffer, from, to);
        }
    }
};

 

(递归) 汉诺塔问题 lintcode 169

原文:https://www.cnblogs.com/Bella2017/p/11482561.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!