λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 120 - Triangle (Medium)

by HandHand 2021. 4. 13.

문제

LeetCode - 120번

풀이 κ³Όμ •

첫번째 ν–‰μ—μ„œ λ§ˆμ§€λ§‰ ν–‰κΉŒμ§€ λ„λ‹¬ν•˜κΈ° μœ„ν•œ 거리의 μ΅œμ†Œ 합을 κ΅¬ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

dp(row, idx) = row ν–‰μ˜ idx μ—΄μ—μ„œ λ§ˆμ§€λ§‰ 행에 λ„λ‹¬ν•˜κΈ° μœ„ν•œ μ΅œμ†Œ 거리 라고 μ •μ˜ν•œλ‹€λ©΄

λ‹€μŒκ³Ό 같은 점화식을 얻을 수 μžˆμŠ΅λ‹ˆλ‹€.


dp[row][idx] = min(dp[row + 1][idx], dp[row + 1][idx + 1]) + triangle[row][idx]

μ½”λ“œ

/**
 * @param {number[][]} triangle
 * @return {number}
 */
var minimumTotal = function (triangle) {
  const INF = 9999999;
  const rowLimit = triangle.length;
  const memo = Array.from(Array(rowLimit), () => Array(rowLimit + 1).fill(-1));

  function dp(row, index) {
    if (row.length >= index) {
      return INF;
    }

    if (row === rowLimit - 1) {
      return triangle[row][index];
    }

    if (memo[row][index] !== -1) {
      return memo[row][index];
    }

    memo[row][index] =
      Math.min(dp(row + 1, index), dp(row + 1, index + 1)) +
      triangle[row][index];

    return memo[row][index];
  }

  const answer = dp(0, 0);

  return answer;
};
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€