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 | class Solution { |
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 Hanota1
2
3
4
5
6
7
8def calculateHanota(count):
stepForOnlyCurrent = 1
if count==1:
return stepForOnlyCurrent
totalCount = stepForOnlyCurrent + calculateHanota(count-1)*2
return totalCount
print(calculateHanota(64))