1 递归分支法
用数学归纳法解决
- n = 1,盘子从A直接移动到C
- n = 2
- n = k,将A上n-1个盘子移动到B,然后将最底下的盘子移动到C,最后将B中的盘子移动到C
class Solution {
public:
void hanota(vector<int>& A, vector<int>& B, vector<int>& C) {
int n = A.size();
move(n, A, B, C);
}
void move(int n, vector<int>& A, vector<int>& B, vector<int>& C) {
if (n == 1) {
C.push_back(A.back());
A.pop_back();
} else {
// 将柱子A上面n-1个盘子从A移动到B
move(n - 1, A, C, B);
// 将柱子A底下最大的盘子移动到柱子C
C.push_back(A.back());
A.pop_back();
// 将柱子B上面n-1个盘子从B移动到C
move(n - 1, B, A, C);
}
}
};
2 输出打印盘子移动过程(快手广告算法二面题)
当n = 3时
代码语言:javascript复制#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void move(int n, vector<int>& A, vector<int>& B, vector<int>& C, string s) {
if (n == 1) {
cout << "盘子" << A.back() << " from " << s[0] << " to " << s[2] << endl;
C.push_back(A.back());
A.pop_back();
return;
}
swap(s[1], s[2]);
move(n - 1, A, C, B, s);
cout << "盘子" << A.back() << " from " << s[0] << " to " << s[1] << endl;
C.push_back(A.back());
A.pop_back();
swap(s[1], s[2]);
swap(s[0], s[1]);
move(n - 1, B, A, C, s);
}
int main() {
int n = 3;
vector<int> A, B, C;
for (int i = n; i > 0; i--)
A.emplace_back(i);
move(n, A, B, C, "ABC");
return 0;
}