题目:
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
链接: http://leetcode.com/problems/climbing-stairs/
斐波那契数列的应用
一刷,用dp做法,注意在建数组时需要明确长度,行8, 否则行12会报错。
1 class Solution(object): 2 def climbStairs(self, n): 3 4 if n == 1: 5 return 1 6 elif n == 2: 7 return 2 8 methods = [0 for i in range(n)] 9 methods[:1] = [1, 2] 10 11 for index in range(2, n): 12 methods[index] = methods[index - 1] + methods[index - 2] 13 return methods[n - 1]
用2个变量表示,节省空间复杂度
class Solution(object): def climbStairs(self, n): if n == 1: return 1 elif n == 2: return 2 first = 1 second = 2 for i in range(2, n): current = first + second first, second = second, current return current
简化初始判断
class Solution(object): def climbStairs(self, n): first, second = 1, 2 for i in range(2, n + 1): first, second = second, first + second return first
矩阵解法,未懂:
1 class Solution(object): 2 def matrix_multiply(self, M, N): 3 a = M[0][0] * N[0][0] + M[0][1] * N[1][0] 4 b = M[0][0] * N[0][1] + M[0][1] * N[1][1] 5 c = M[1][0] * N[0][0] + M[1][1] * N[1][0] 6 d = M[1][0] * N[0][1] + M[1][1] * N[1][1] 7 return [[a, b], [c, d]] 8 9 def climbStairs(self, n): 10 if n == 1: 11 return 1 12 13 ret = [[1, 0], [0, 1]] 14 test_matrix = [[1, 1], [1, 0]] 15 while n: 16 if n % 2: 17 ret = self.matrix_multiply(ret, test_matrix) 18 n /= 2 19 test_matrix = self.matrix_multiply(test_matrix, test_matrix) 20 21 return ret[0][0]
2/14/2017, Java, 斐波那契数列解法
1 public class Solution { 2 public int climbStairs(int n) { 3 if (n <= 2) return n; 4 int[] ret = new int[n]; 5 ret[0] = 1; 6 ret[1] = 2; 7 8 for(int i = 2; i < n; i++) { 9 ret[i] = ret[i-1] + ret[i-2]; 10 } 11 return ret[n-1]; 12 } 13 }