题解 | #汉诺塔问题#
汉诺塔问题
https://www.nowcoder.com/practice/7d6cab7d435048c4b05251bf44e9f185
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return string字符串vector */ vector<string> res; vector<string> getSolution(int n) { f(n, "left", "mid", "right"); return res; } void f(int n, string x, string y, string z){ if(n == 0) return; f(n - 1, x, z, y); res.push_back("move from " + x + " to " + z); f(n - 1, y, x, z); } }; 三个参数写法 void hanoi(int n, char a, char b){ char help = char(198 - a - b); // 辅助塔help 除了起点和终点之外的一个塔 if(n == 1){ cout << "disk" << n << ":" << a << "->" << b << endl; } else{ hanoi(n - 1, a, help); cout << "disk" << n << ":" << a << "->" << b << endl; hanoi(n - 1, help, b); } } 四个参数写法 void hanoi(int n, char a, char b, char help) // 从起点a 到终点 b 辅助塔help { if(n == 1){ cout << "disk" << n << ":" << a << "->" << b << endl; } else{ hanoi(n - 1, a, help, b); // 辅助塔为b 从a移动到help cout << "disk" << n << ":" << a << "->" << b << endl; hanoi(n - 1, help, b, a); // 辅助塔为a 从help移动到b } }