GuoXin Li's Blog

LeetCode-Hanota LCCI

字数统计: 328阅读时长: 2 min
2020/11/20 Share

08.06. Hanota LCCI

In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:

(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto another tower.
(3) A disk cannot be placed on top of a smaller disk.

Write a program to move the disks from the first tower to the last using stacks.

Example1:

Input: A = [2, 1, 0], B = [], C = []
Output: C = [2, 1, 0]

Example2:

Input: A = [1, 0], B = [], C = []
Output: C = [1, 0]
Note:

A.length <= 14

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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();
return;
}
move(n-1, A, C, B);
C.push_back(A.back());
A.pop_back();
move(n-1, B, A, C);
}
};

time complexity: $O(2^n-1)$ . It’s the moving times.

space complexity: $O(1)$

Key Solution:

  • wanna resolve n number, first to resolve n-1
  • put n-1 number of A into B using C
  • push_back A.back into C. (It’s a half answer that A.back must be at the bottum of C)
  • pop A.back(). (=delete A.back)
  • put n-1 number of B into C using A

For count how times of Hanota

1
2
3
4
5
6
7
8
def calculateHanota(count):
stepForOnlyCurrent = 1
if count==1:
return stepForOnlyCurrent
totalCount = stepForOnlyCurrent + calculateHanota(count-1)*2
return totalCount

print(calculateHanota(64))

CATALOG
  1. 1. 08.06. Hanota LCCI
    1. 1.1. Example1:
    2. 1.2. Example2: