题解 | #汉诺塔问题#

汉诺塔问题

https://www.nowcoder.com/practice/7d6cab7d435048c4b05251bf44e9f185

//递归的方法
class Solution {
public:
    void hanno(int n,vector<string> &ans,string from,string to,string other ){
        if(n==1){
            string ansi="move from "+from+" to "+to;
            ans.push_back(ansi);
        }      
        else{
            hanno(n-1,ans,from,other,to);
            string ansi="move from "+from+" to "+to;
            ans.push_back(ansi);
            hanno(n-1,ans,other,to,from);
        }
    }
    vector<string> getSolution(int n) {
        string from="left";
        string to="right";
        string other="mid";
        vector<string> ans;
        hanno(n,ans,from,to,other);
        return ans;
    }
};
全部评论
可参考左程云的算法课程
点赞 回复 分享
发布于 2023-08-02 15:12 陕西

相关推荐

不愿透露姓名的神秘牛友
昨天 14:18
点赞 评论 收藏
分享
06-19 19:06
门头沟学院 Java
码农索隆:别去东软,真学不到东西,真事
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务