1. Recursive: We can use recursive way to solve this problem: O(n) = O(n - 1) + O(n - 2). 2. DP: This method also very straightforward. dp[i] means how many ways to reach level i. So it would take O(n) time and O(n) space to solve the problem. 3. Two pointers: We also can use to pointers to store the info. It is like DP. But the space is reduced to O(1).
This question is very easy. But the corner case must be considered in. 1. negative n. 2. n equals to 0. Then we can using recursive method to solve this problem. Here is the code: Additional throughout: how about n is also double?
For this problem, BFS is better than DFS. DFS, it's like from the first char to the last char of the word, try to match the dictionary. However, if there is not match, then start from last matching char and do the same again. So it is not efficiency. Using BFS, it is like Level traverse a tree. So it would reduce the times for matching. Here is the code. Using two queue( the distance Queue is not required. it just used for store the distance every time generate.) to do the BFS. (when mention the BFS, the first thought must be Queue. LOL).