위 그림은 크기가 5인 정수 삼각형의 한 모습이다.
맨 위층 7부터 시작해서 아래에 있는 수 중 하나를 선택하여 아래층으로 내려올 때, 이제까지 선택된 수의 합이 최대가 되는 경로를 구하는 프로그램을 작성하라. 아래층에 있는 수는 현재 층에서 선택된 수의 대각선 왼쪽 또는 대각선 오른쪽에 있는 것 중에서만 선택할 수 있다.
삼각형의 크기는 1 이상 500 이하이다. 삼각형을 이루고 있는 각 수는 모두 정수이며, 범위는 0 이상 9999 이하이다.
첫째 줄에 삼각형의 크기 n(1 ≤ n ≤ 500)이 주어지고, 둘째 줄부터 n+1번째 줄까지 정수 삼각형이 주어진다.
첫째 줄에 합이 최대가 되는 경로에 있는 수의 합을 출력한다.
- 다이나믹 프로그래밍
import java.util.*;
import java.io.*;
public class Main {
static int N;
static int arr[][];
static Integer dp[][];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
arr = new int[N][N];
dp = new Integer[N][N];
StringTokenizer st;
for(int i=0; i<N; i++) {
st = new StringTokenizer(br.readLine(), " ");
for(int j=0; j<i+1; j++)
arr[i][j] = Integer.parseInt(st.nextToken());
}
for(int i=0; i<N; i++)
dp[N-1][i] = arr[N-1][i];
System.out.println(Func(0, 0));
}
static int Func(int depth, int location) {
if(depth == N-1)
return dp[depth][location];
if(dp[depth][location] == null)
dp[depth][location] = Math.max(Func(depth+1, location), Func(depth+1, location+1)) + arr[depth][location];
return dp[depth][location];
}
}
arr 배열은 삼각형의 원소들을 담고, dp 배열에는 구간 합을 담는다.
이 문제를 풀면서 어려웠던 것은 마지막 줄 원소를 dp에 저장해놓는 것이였다.