https://oj.leetcode.com/problems/climbing-stairs/
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];
}
}
}
};
'풀어본 Algorithm 문제 정리' 카테고리의 다른 글
[OJ.leetcode] symmetric-tree (0) | 2014.06.30 |
---|---|
[OJ.leetcode] populating-next-right-pointers-in-each-node (0) | 2014.06.29 |
[OJ.leetcode] Binary Tree Inorder Traversal (0) | 2014.06.29 |
[OJ.leetcode] Validate Binary Search Tree (0) | 2014.06.29 |
[OJ.leetcode] Convert Sorted Array to Binary Search Tree (0) | 2014.06.29 |