DuckingRacoon
프로그래머스 | [DP] 정수 삼각형 본문
출처
🌐 코딩테스트 연습 - 정수 삼각형 | 프로그래머스 스쿨
문제
문제 설명

위와 같은 삼각형의 꼭대기에서 바닥까지 이어지는 경로 중, 거쳐간 숫자의 합이 가장 큰 경우를 찾아보려고 합니다. 아래 칸으로 이동할 때는 대각선 방향으로 한 칸 오른쪽 또는 왼쪽으로만 이동 가능합니다. 예를 들어 3에서는 그 아래칸의 8 또는 1로만 이동이 가능합니다.
삼각형의 정보가 담긴 배열 triangle이 매개변수로 주어질 때, 거쳐간 숫자의 최댓값을 return 하도록 solution 함수를 완성하세요.
제한사항
- 삼각형의 높이는 1 이상 500 이하입니다.
- 삼각형을 이루고 있는 숫자는 0 이상 9,999 이하의 정수입니다.
입출력 예시
triangle result
| [[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]] | 30 |
풀이
1차 풀이
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<vector<int>> triangle)
{
vector<int> lastLevel = { 0 };
for (const vector<int>& row : triangle)
{
vector<int> current;
for (int i = 0; i < row.size(); i++)
{
int index = (i == row.size()-1)? i - 1: i;
int jndex = (i == 0)? i: i - 1;
current.push_back( max(lastLevel[index] + row[i], lastLevel[jndex] + row[i]) );
}
lastLevel = current;
}
int answer = *max_element(lastLevel.begin(), lastLevel.end());
return answer;
}
2차 풀이 (리팩토링)
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<vector<int>> triangle)
{
vector<int> prev = { 0 };
for (const vector<int>& row : triangle)
{
vector<int> curr;
for (int i = 0; i < row.size(); i++)
{
int left = (i == 0)? i: i - 1;
int right = (i == row.size()-1)? i - 1: i;
curr.push_back( row[i] + max(prev[left], prev[right]) );
}
prev = curr;
}
return *max_element(prev.begin(), prev.end());
//int answer = *max_element(prev.begin(), prev.end());
//return answer;
}
'알고리즘' 카테고리의 다른 글
| 프로그래머스 | [DP] 등굣길 (0) | 2025.09.03 |
|---|---|
| 프로그래머스 | 야근지수 (0) | 2025.09.03 |
| 프로그래머스 | 봉인된 주문 (0) | 2025.09.03 |
| 프로그래머스 | [DFS/BFS] 여행경로 (0) | 2025.09.03 |
| 프로그래머스 | 이중우선순위큐 (0) | 2025.09.03 |