2742. Painting the Walls

Created
Oct 14, 2023 01:28 PM
Modified
Last updated December 7, 2023
Tag
Leet Code
Hard
Daily Question
Got Help
  • λͺ»ν’€μ—ˆλ˜ 문제.
    • costκ°€ 적은 wall 순으둜 μ •λ ¬ν•˜μ—¬ μ‹œκ°„μ˜ 합이 λ‚˜λ¨Έμ§€ array의 길이와 κ°™κ±°λ‚˜ μ»€μ§ˆλ•Œ κΉŒμ§€ costλ₯Ό λ”ν•˜λŠ” λ°©μ‹μœΌλ‘œ κ΅¬ν•˜μ˜€μœΌλ‚˜ μ‹€νŒ¨.
    • 상황에 λ”°λΌμ„œλŠ” costκ°€ λ†’μ§€λ§Œ time도 λ†’μ•„μ„œ ν•˜λ‚˜λΌλ„ 덜 paid painterλ₯Ό μ‚¬μš©ν•˜λŠ” κ²½μš°κ°€ μœ λ¦¬ν•  수 있기 λ•Œλ¬ΈμΈ κ²ƒμœΌλ‘œ 보인닀.
    • DPμ—μ„œ μ–΄λ €μš΄ 뢀뢄은 μ–΄λ–€ 것을 memoization ν• μ§€ μ•Œμ•„λ‚΄λŠ” 뢀뢄인 것 κ°™λ‹€.
  • 처음 indexλΆ€ν„° λκΉŒμ§€ νƒμƒ‰ν•΄λ‚˜κ°€λ©° μ΅œμ†Œμ˜ costλ₯Ό μ°ΎλŠ”λ‹€.
    • ν˜„μž¬ indexλ₯Ό 선택할 경우 costλŠ” λ‹€μŒ 두 κ°’μ˜ 합이닀.
      • ν˜„μž¬ index의 cost cost[i]
      • λ‹€μŒ index i + 1λ₯Ό νƒμƒ‰ν•˜μ—¬ κ²°μ •λœ cost (단, 이미 μΉ ν•΄μ§„ 벽의 μˆ«μžλŠ” painted + 1 + time[i]둜 μ •ν•΄μ§„λ‹€)
        • 1은 ν˜„μž¬ μ„ νƒλœ 벽에 ν•΄λ‹Ήλ˜λŠ” 숫자
        • time[i]은 ν˜„μž¬ μ„ νƒλœ 벽을 μΉ ν•˜λŠ” μ‹œκ°„μœΌλ‘œ ν•΄λ‹Ή μ‹œκ°„ λ™μ•ˆ free painterκ°€ μΆ”κ°€λ‘œ 벽을 μΉ ν•  수 μžˆλ‹€
    • ν˜„μž¬ indexλ₯Ό μ„ νƒν•˜μ§€ μ•ŠλŠ” 경우 costλŠ” λ‹€μŒ 값이 λœλ‹€.
      • λ‹€μŒ index i + 1λ₯Ό νƒμƒ‰ν•˜μ—¬ κ²°μ •λœ cost (단, 이미 μΉ ν•΄μ§„ 벽의 μˆ«μžλŠ” painted둜 μ •ν•΄μ§„λ‹€)
        • ν˜„μž¬ 벽을 paid painterκ°€ μΉ ν•˜μ§€ μ•ŠκΈ°λ‘œ ν–ˆμœΌλ―€λ‘œ μΉ ν•΄μ§„ 벽의 숫자 paintedλŠ” 변함이 μ—†λ‹€.
      class Solution { public: int paintWalls( vector<int>& cost, vector<int>& time, vector<vector<int>>& dp, int i, int painted) { if (painted >= cost.size()) return 0; if (i >= cost.size()) return 1e9; if (dp[i][painted] != -1) return dp[i][painted]; int choose = cost[i] + paintWalls(cost, time, dp, i + 1, painted + 1 + time[i]); int notChoose = paintWalls(cost, time, dp, i + 1, painted); return dp[i][painted] = min(choose, notChoose); } int paintWalls(vector<int>& cost, vector<int>& time) { vector<vector<int>> dp( cost.size(), vector<int>(cost.size() + 1, -1)); return paintWalls(cost, time, dp, 0, 0); } };