198. 打家劫舍
小于 1 分钟
198. 打家劫舍中等
解题思路:
动态规划
状态转移方程:dp[k] = Math.max(dp[k-1], nums[k-1] + dp[k-2]);
class Solution {
public int rob(int[] nums) {
if (nums.length == 0) {
return 0;
}
int len = nums.length;
int[] dp = new int[N+1];
dp[0] = 0;
dp[1] = nums[0];
for (int k = 2; k <= N; k++) {
dp[k] = Math.max(dp[k-1], nums[k-1] + dp[k-2]);
}
return dp[len];
}
}
function rob(nums: number[]): number {
if (nums.length == 0) {
return 0;
}
let len:number = nums.length;
let dp: number[] = [];
dp[0] = 0;
dp[1] = nums[0];
for (let k: number = 2; k <= len; k++) {
dp[k] = Math.max(dp[k-1], nums[k-1] + dp[k-2]);
}
return dp[len];
};
Powered by Waline v2.15.5