Skip to content

Instantly share code, notes, and snippets.

@sopherwang
Created September 14, 2014 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sopherwang/5101a962f04666b21ee1 to your computer and use it in GitHub Desktop.
Save sopherwang/5101a962f04666b21ee1 to your computer and use it in GitHub Desktop.
Climbing Stairs
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