
-Code
class Solution {
public int minCostClimbingStairs(int[] cost) {
int length = cost.length;
int[] dp = new int[length];
// 1번과 2번 계단은 시작점이므로 그 계단이 최소 비용
dp[0] = cost[0];
dp[1] = cost[1];
// 2번 계단 부터 시작
for (int i = 2; i < length; i++) {
// 현제 계단 비용 + 올 수있는 계간의 최소 비용
dp[i] = cost[i] + Math.min(dp[i - 1], dp[i - 2]);
}
// 정상에 도달하기 1 or 2개 전 계단 비용 중 작은거 출력
return Math.min(dp[length-1] , dp[length - 2]);
}
}
처음에 기본값을 세팅 안 하고 해서 복잡하게 작성하고 해결은 했습니다. 그 이후 다른 방법은 없을까 해서 dp의 0, 1번을 세팅하면 덜 복잡해져서 해당 코드로 바꿨습니다.
'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [백준/Java] 27487번 One and Two (0) | 2026.01.01 |
|---|---|
| [LeetCode/Java] Product of Array Except Self (0) | 2025.12.31 |
| [LeetCode/Java] N-th Tribonacci Number (0) | 2025.12.31 |
| [백준/Java] 3018번 캠프파이어 (0) | 2025.12.31 |
| [LeetCode/Java] Guess Number Higher or Lower (0) | 2025.12.31 |