개발자/algorithm

LeetCode, Climbing Stairs (Java)

성찬쿤 2021. 1. 5. 23:18

leetcode.com/problems/climbing-stairs/

 

Climbing Stairs - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

간단한 dp 문제이다.

class Solution {
	public int climbStairs(int n) {
		int[] count = new int[n + 1];
		count[0] = 0;
		count[1] = 1;
		count[2] = 2;
		count[3] = 3;

		for (int i = 4; i <= n; i++) {
			count[i] = count[i - 1] + count[i - 2];
		}

		return count[n];
	}
}