Optimal: recursive three steps
Time O(2ⁿ) Space O(n) stack (plus the output)solve(n, from, to, via): if n == 0 return. solve(n − 1, from, via, to); record from->to; solve(n − 1, via, to, from).
n = 2peg 1(stack)
peg 2(stack)
empty
peg 3(stack)
empty
Step 1/4Disc 2 (big) is under disc 1 (small). Step 1: move the n − 1 = 1 small disc to peg 2.
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<String> hanoi(int n) {
List<String> moves = new ArrayList<>();
solve(n, 1, 3, 2, moves);
return moves;
}
private void solve(int n, int from, int to, int via, List<String> moves) {
if (n == 0) return;
solve(n - 1, from, via, to, moves);
moves.add(from + "->" + to);
solve(n - 1, via, to, from, moves);
}
}Verdict: 2ⁿ − 1 moves is the minimum possible, so no algorithm can do better.