Cute Running Puppy

algorithm/Programmers

[programmers] ์ •์ˆ˜ ์‚ผ๊ฐํ˜• - Python, Java

R.silver 2024. 7. 1. 20:46
๋ฐ˜์‘ํ˜•

๐Ÿ“–๋ฌธ์ œ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ •์ˆ˜ ์‚ผ๊ฐํ˜• | ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์Šค์ฟจ (programmers.co.kr)

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

โœจํ•ต์‹ฌ ๋‚ด์šฉ 

- ๊ฑฐ์ณ๊ฐ„ ์ˆซ์ž์˜ ํ•ฉ์ด ๊ฐ€์žฅ ํฐ ๊ฒฝ์šฐ ์ฐพ๊ธฐ 
- ์•„๋ž˜ ์นธ์œผ๋กœ ์ด๋™ํ•  ๋•Œ๋Š” ๋Œ€๊ฐ์„  ๋ฐฉํ–ฅ์œผ๋กœ ํ•œ ์นธ "์˜ค๋ฅธ์ชฝ ๋˜๋Š” ์™ผ์ชฝ"์œผ๋กœ๋งŒ ์ด๋™ ๊ฐ€๋Šฅ

 

๐Ÿค”ํ•ด๊ฒฐ ์•„์ด๋””์–ด 

์œ ํ˜•: DP
 
ํ˜„์žฌ ์œ„์น˜(i, j)์—์„œ ์ตœ๋Œ“๊ฐ’์ด ๋˜๋ ค๋ฉด
์™ผ์ชฝ ์œ„(i-1, j-1) vs ์˜ค๋ฅธ์ชฝ ์œ„(i-1, j) ์ค‘ ์–ด๋Š ๋ฐฉํ–ฅ์œผ๋กœ ์™€์•ผ ์ตœ๋Œ“๊ฐ’์ด ๋˜๋Š”์ง€ ์ฐพ๊ธฐ


โœ…์ •๋‹ต ์ฝ”๋“œ (Python)

def solution(triangle):
    n = len(triangle)
    m = len(triangle[n - 1])

    # 1. dp ์ •์˜ - (i, j) ์œ„์น˜๊นŒ์ง€์˜ ๊ฒฝ๋กœ ์ค‘ ์ˆซ์ž์˜ ํ•ฉ์˜ ์ตœ๋Œ“๊ฐ’
    dp = [[0 for _ in range(n)] for _ in range(m)]

    # 2. dp ์ดˆ๊ธฐํ™”
    # 2-1. dp[0][0] ์ดˆ๊ธฐํ™”
    dp[0][0] = triangle[0][0]

    for i in range(1, n):
        # // 2-2. dp[i][0] ์ดˆ๊ธฐํ™”
        dp[i][0] = dp[i - 1][0] + triangle[i][0]
        
        # //2-3. dp[i][cnt] ์ดˆ๊ธฐํ™”
        dp[i][i] = dp[i - 1][i - 1] + triangle[i][i]

    # 3. ์ ํ™”์‹
    for i in range(2, n):
        for j in range(1, i):
            dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i][j]

    return max(dp[n - 1])

 

โœ…์ •๋‹ต ์ฝ”๋“œ (Java)

class Solution {
    public int solution(int[][] triangle) {
        int n = triangle.length;
        int m = triangle[n-1].length;

        // 1. dp ์ •์˜ - (i, j) ์œ„์น˜๊นŒ์ง€์˜ ๊ฒฝ๋กœ ์ค‘ ์ˆซ์ž์˜ ํ•ฉ์˜ ์ตœ๋Œ“๊ฐ’
        int[][] dp = new int[n][m];

        // 2. dp ์ดˆ๊ธฐํ™”
        // 2-1. dp[0][0] ์ดˆ๊ธฐํ™”
        dp[0][0] = triangle[0][0];

        for (int i = 1 ; i < n; i++) {
            // 2-2. dp[i][0] ์ดˆ๊ธฐํ™”
            dp[i][0] = dp[i-1][0] + triangle[i][0];

            //2-3. dp[i][cnt] ์ดˆ๊ธฐํ™”
            dp[i][i] = dp[i-1][i-1] + triangle[i][i];
        }

        // 3. ์ ํ™”์‹
        for (int i = 2; i < n; i++) {
            for (int j = 1; j < i; j++) {
                dp[i][j] = Math.max(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j];
            }
        }

        // 4. output
        int mx = 0;
        for (int j = 0; j < m; j++)
            mx = Math.max(mx, dp[n-1][j]);
        return mx;
    }
}

 
 

๋ฐ˜์‘ํ˜•