λ¬Έμ
νμ΄ κ³Όμ
λλμ§μ ν΅ν΄ μ»μ μ μλ μ΅λ μμ΅μ ꡬνλ λμ κ³νλ²
λ¬Έμ μ
λλ€.
λ§μ½ dp(house) = house μμλΆν° λ§μ§λ§ μ§κΉμ§ λλμ§μ ν΅ν΄ μ»μ μ μλ μ΅λ μμ΅
μ΄λΌκ³ νλ€λ©΄,
λ€μκ³Ό κ°μ μ νμμ μΈμΈ μ μμ΅λλ€.
dp(house) = max(dp(house+1), dp(house + 2) + cost[house])
μ¬κΈ°μ λ κ°μ§λ‘ λλμ΄μ§λ μ΄μ λ νμ¬ house
μμΉμμ λλμ§μ νλ κ²κ³Ό μνλ κ² μ΄λ κ²
λ κ°μ§ κ²½μ°κ° μκΈ° λλ¬Έμ
λλ€.
μ½λ
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function (nums) {
const memo = new Array(nums.length).fill(-1);
function dp(i) {
if (i >= nums.length) return 0;
if (i === nums.length - 1) return nums[i];
if (memo[i] !== -1) return memo[i];
memo[i] = Math.max(dp(i + 1), dp(i + 2) + nums[i]);
return memo[i];
}
return dp(0);
};
λ°μν
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 17 - Letter Combinations of a Phone Number (Medium) (0) | 2021.03.02 |
---|---|
LeetCode 230 - Kth Smallest Element in a BST (Medium) (0) | 2021.03.02 |
LeetCode 22 - Generate Parentheses (Medium) (0) | 2021.03.02 |
LeetCode 62 - Unique Paths (Medium) (0) | 2021.03.02 |
LeetCode 121 - Best Time to Buy and Sell Stock (Easy) (0) | 2021.03.02 |
π¬ λκΈ