-
[LeetCode] 120. TriangleLeetCode 2021. 12. 3. 17:12728x90
https://leetcode.com/problems/triangle/
Triangle - 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
Triangle - Medium

위 예시와 같이 삼각형모양으로 수가 나열되어 있다. 이 때, 가장 위에서부터 출발하여 삼각형 아래줄의 왼쪽 또는 오른쪽으로 이동할 수 있다고 할 때, 경로상에 있는 모든 수들의 합이 가장 작을 때를 구하는 문제다.
흔히 보이는 dp문제다.
2 3 4 6 5 7 4 1 8 3 일단 가장 위의 2 위치에 있을 때, 다음엔 3 또는 4로 갈 수 있고,
5의 위치에 있다면 1 또는 8로 갈 수 있다.
즉 (i, j) -> (i+1, j) 또는 (i, j) -> (i+1, j+1)로 이동할 수 있다.
반대로 (i, j)로 올 수 있는 방법은 (i-1, j-1) 또는 (i-1, j) 에서 이동하는 방법인데,
이를 이용하면 (i, j) 에서 가장 작은 경로합은 (i-1, j-1) 과 (i-1, j)의 경로 중 더 작은 경로에서 오는 경우가 된다.
즉, dp[i][j] = triangle[i][j] + min(dp[i-1][j-1], dp[i-1][j]) 가 된다.
전체 풀이 코드
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { int m = INT_MAX; for (int i=1; i<triangle.size(); i++) { triangle[i][0] += triangle[i-1][0]; triangle[i].back() += triangle[i-1].back(); for (int j=1; j<triangle[i].size()-1; j++) triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j]); } for (int n:triangle.back()) m = min(m, n); return m; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 1306. Jump Game III (0) 2021.12.09 [LeetCode] 563. Binary Tree Tilt (0) 2021.12.08 [LeetCode] 328. Odd Even Linked List (0) 2021.12.02 [LeetCode] 198. House Robber (0) 2021.12.01 [LeetCode] 238. Product of Array Except Self (0) 2021.11.27