티스토리 뷰
Question
Given a triangle array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
삼각형 배열이 주어지면 위에서 아래로 최소 경로 합계를 반환합니다.
각 단계마다 아래 행의 인접한 번호로 이동할 수 있습니다. 더 공식적으로 말하면, 현재 행의 인덱스 i에 있으면 다음 행의 인덱스 i 또는 인덱스 i 1로 이동할 수 있습니다.
제약사항
- 1 <= triangle.length <= 200
- triangle[0].length == 1
- triangle[i].length == triangle[i - 1].length + 1
- -104 <= triangle[i][j] <= 104
Solution
가능한 최선의 수행 시간(Best Conceivable Runtime(BCR)
- 모든원소를 한번 씩은 봐야하므로 O(n^2)
문제를 풀 때 고려한 사항
- 손으로 풀어보는 것이 도움이 될 때가 있다.
Solution1 : DP
2
3 4
6 5 7
4 1 8 3
위 예를 손으로 직접 풀이 해본다면,
2
5, 6
11, 10, 13
15, 11, 18, 21
이런식이다.
즉 현재 원소의 까지의 path가 최소path라 가정한다면, path의 값은 현재 값 + 이전의 path값 2개 중 작은값을 더하는 것이 최소값이 된다. 그렇다면 이 값을 계속 기록해가며 본다면 가능한 모든 Path에서의 최소값을 구할 수 있다.
다만 위에서 부터 차례로 합쳐 계산하는것 보다 아래서부터 올라가는 방식으로 min값을 구한다면, 더 쉽게 구할 수 있다.
C++
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int last_row = triangle.size() - 1;
for (int i = last_row - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
triangle[i][j] = triangle[i][j] + min(triangle[i + 1][j], triangle[i + 1][j + 1]);
}
}
return triangle[0][0];
}
};
Python
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
n = len(triangle) - 1
for i in range(n - 1, -1, -1):
for j in range(0, i + 1):
triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1])
return triangle[0][0]
- Time complexity : O(n^2)
- Space Complexity : O(n)
출처 : https://leetcode.com/problems/triangle/description/?envType=study-plan-v2&envId=top-interview-150
Triangle - LeetCode
Can you solve this real interview question? Triangle - Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you
leetcode.com
'IT > Problem Solving' 카테고리의 다른 글
[C++] LeetCode : Merge Sorted Array (0) | 2024.03.01 |
---|---|
Substring, Subsequence, Subset, SubArray 차이 (0) | 2022.10.28 |
[C++] Interview Question : Find Minimum Canoe (0) | 2022.08.31 |
[C++] LeetCode : Isomorphic Strings (0) | 2022.08.25 |
[C++] Interview Question : Pots of gold game (0) | 2022.08.25 |
- Total
- Today
- Yesterday
- ProblemSolving
- Interview
- 반드시 알아야 할 자료구조
- PS
- interview question
- algorithm
- LeetCode
- 인터뷰
- 맛집
- 속초 맛집
- 리트코드
- 트리
- Tree
- 코딩인터뷰
- 속초
- rust
- Problem Solving
- 알고리즘
- C++
- 자료구조
- DP
- 러스트 기초
- 기술면접
- coding interview
- 러스트 입문
- Medium
- 솔직후기
- 러스트 배우기
- 내돈내산
- 러스트
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |