본문 바로가기

알고리즘/프로그래머스

[프로그래머스] 정수 삼각형 / JAVA

문제링크 : https://programmers.co.kr/learn/courses/30/lessons/43105

class Solution {
    public static int dp[][];
    public static int triangles[][];
    public static int dfs(int y,int x){
        if(y==triangles.length-1) return dp[y][x] = triangles[y][x];
        if(dp[y][x] != -1) return dp[y][x];

        return dp[y][x] = Math.max(dfs(y+1,x),dfs(y+1,x+1)) + triangles[y][x];
    }
    public static int solution(int[][] triangle) {
        int answer = 0;
        int N = triangle.length;
        dp = new int[N][N];
        triangles = new int[N][N];
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                dp[i][j] = -1;
            }
        }
        for(int i=0;i<N;i++){
            for(int j=0;j<i+1;j++){
                triangles[i][j] = triangle[i][j];
            }
        }
        answer = dfs(0,0);
        return answer;
    }
}