Backtracking (time exceeded)
1 | class Solution { |
Remarks:
- TC: $O(2^n)$, SC: $O(n)$.
Dynamic Programming
1 | class Solution { |
Remarks:
- TC: $O(n)$, SC: $O(1)$.
- Ideas:
This is exactly same as a fibonacci sequence.
To achieve a position $n$ ($n\geq2$), we have to ways: (a) reach $n$ from $n-1$ by increasing 1; (b) reach $n$ from $n-2$ by increasing 2. Each method have only one choice, so all paths that can reach $n$, noted as $f(n)$, is the sum of $f(n-1)$ and $f(n-2)$, i.e.,
$$
f(n) = f(n-1) + f(n-2)
$$
This is the State Transition Equation (状態方程式) for this problem.
Additioanlly, $f(1) = 1$, $f(2)=2$.