Skip to content

Instantly share code, notes, and snippets.

@walkingtospace
Last active August 29, 2015 14:02
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 walkingtospace/4f828b96081ab0308cbc to your computer and use it in GitHub Desktop.
Save walkingtospace/4f828b96081ab0308cbc to your computer and use it in GitHub Desktop.
계단 수 세기 문제 (recursive + dynamic programming)
//https://oj.leetcode.com/problems/climbing-stairs/
Q. 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?
//n=2는 n=1에서 1걸음 더 간것
//n=3은 n=2에서 1걸음 더 간것 + n=1에서 2걸음
//n=4는 n=3에서 1걸음 더 간것 + n=2에서 2걸음
// .. => 재귀함수로 n을 감소시키면서 풀면 되겠다.
// n>2, f(n) = f(n-1) + f(n-2) 성립
//f(3) = f(2) + f(1) = 3
//f(4) = f(3) + f(2) = 3 + 2 = 5
//time over : dynamic programming 적용하자.
class Solution {
public:
int steps[1024];
int climbStairs(int n) {
if(n == 1) {
if(steps[1] == 0) {
steps[1] = 1;
return steps[1];
} else {
return steps[1];
}
}
else if(n == 2) {
if(steps[2] == 0) {
steps[2] = 2;
return steps[2];
} else {
return steps[2];
}
}
else if(n >= 3) {
if(steps[n] == 0) {
steps[n] = climbStairs(n-1) + climbStairs(n-2);
return steps[n];
} else {
return steps[n];
}
}
}
};
//복습
int steps[1024];
int countway(int n) {
if(n <= 1) {
steps[n] = 1;
return steps[n];
}
if(n == 2) {
steps[n] = 2;
return steps[n];
}
if(n >= 3) {
if( steps[n] == 0 ) {
steps[n] = countway(n-1) + countway(n-2);
}
return steps[n];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment