代码随想录算法训练营第五十天|198.打家劫舍 ● 213.打家劫舍II ● 337.打家劫舍III

198. 打家劫舍

方法1:

int rob(int* nums, int numsSize){
    if (numsSize == 0) return 0;
    if (numsSize == 1) return nums[0];
    int dp[numsSize];
    memset(dp, 0, numsSize);
    int i;
    dp[0] = nums[0];
    dp[1] = fmax(nums[0], nums[1]);
    for (i = 2; i < numsSize; i++)
    {
        dp[i] = fmax(dp[i-1], dp[i-2] + nums[i]);
    }
    return fmax(dp[numsSize-1], dp[numsSize-2]);
}

方法2:

int rob(int* nums, int numsSize){
    if (numsSize == 0) return 0;
    if (numsSize == 1) return nums[0];
    int i;
    nums[1] = fmax(nums[0], nums[1]);
    for (i = 2; i < numsSize; i++)
    {
        nums[i] = fmax(nums[i-1], nums[i-2] + nums[i]);
    }
    return fmax(nums[numsSize-1], nums[numsSize-2]);
}

213. 打家劫舍 II

int robRange(int *nums, int start, int end)
{   int dp[end+1];
    dp[start] = nums[start];
    dp[start+1] = fmax(nums[start], nums[start+1]);
    for (int i=start+2; i <= end; i++)
    {
        dp[i] = fmax(dp[i-1], dp[i-2] + nums[i]);
    }
    return dp[end];
}

int rob(int* nums, int numsSize){
    if (numsSize == 1) return nums[0];
    if (numsSize == 2) return fmax(nums[0], nums[1]);
    return fmax(robRange(nums, 0, numsSize-2), robRange(nums, 1, numsSize-1));
}

337. 打家劫舍 III

 //记录节点最高金额
typedef struct status {
    int select;
    int notselect;
} node;

node robTree(struct TreeNode* cur)
{    // 节点为空返回0
    if (cur == NULL) {
        return (node){0,0};
    }
    node l = robTree(cur->left);
    node r = robTree(cur->right);
    // 选择当前节点所得金额
    int select = cur->val + l.notselect + r.notselect;
    int notselect = fmax(l.select, l.notselect) + fmax(r.select, r.notselect);
    return (node){select, notselect};
}

int rob(struct TreeNode* root){
    node status = robTree(root);
    return fmax(status.select, status.notselect);
}

你可能感兴趣的:(代码随想录算法,算法,数据结构,c语言,leetcode)