Created
September 14, 2014 21:52
-
-
Save sopherwang/5101a962f04666b21ee1 to your computer and use it in GitHub Desktop.
Climbing Stairs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int climbStairsDP(int n) | |
{ | |
//dp | |
//dp[i]: how many ways to reach i.(i < n) | |
if (n <= 1) | |
{ | |
return n; | |
} | |
int[] dp = new int[n + 1]; | |
dp[0] = 1; | |
dp[1] = 1; | |
for (int i = 2; i <= n; i++) | |
{ | |
dp[i] = dp[i - 1] + dp[i - 2]; | |
} | |
return dp[n]; | |
} | |
public int climbStairs(int n) | |
{ | |
// Note: The Solution object is instantiated only once and is reused by each test case. | |
int p = 1, q = 1; | |
for (int i = 2; i <= n; i++) | |
{ | |
int temp = q; | |
q += p; | |
p = temp; | |
} | |
return q; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment