You are climbing a stair case. It takesNSteps 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?
1: The following uses a recursive method, but it will time out.
1 class Solution { 2 public: 3 int total_steps=0; 4 int climbStairs(int n) { 5 if(n==0) 6 { 7 total_steps++; 8 } 9 else10 {11 if(n>=1)12 {13 climbStairs(n-1);14 }15 if(n>=2)16 {17 climbStairs(n-2);18 }19 }20 return total_steps;21 }22 };
2: solve the problem with dynamic planning. The Code is as follows:
1 class Solution { 2 public: 3 int total_steps=0; 4 int climbStairs(int n) { 5 if(n==1) return 1; 6 if(n==2) return 2; 7 int solutions[1000]; 8 solutions[0]=0; 9 solutions[1]=1;10 solutions[2]=2;11 int i=3;12 while(i<=n)13 {14 solutions[i]=solutions[i-1]+solutions[i-2];15 i++;16 }17 return solutions[n];18 }19 };
Climbing stairs <leetcode>