Middle-题目58:213. House Robber II

原创 2016年05月31日 16:29:17

题目原文:
Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
题目大意:
Easy-题目26,但是现在房子围成了环形,仍然求最大利益。
题目分析:
分第一家是否偷讨论,如果偷第一家,那么最后一家不能偷,则退化成第一家到倒数第二家的线性问题,如果不偷第一家,那么相当于从第二家到最后一家的线性问题。
源码:(language:c)

int rob(int* nums, int numsSize) {
    if(numsSize==0)
        return 0;
    else if(numsSize==1)
        return nums[0];
    else if(numsSize==2)
        return nums[0]>nums[1]?nums[0]:nums[1];
    else
        return max(rob1(nums,numsSize-1),rob1(nums+1,numsSize-1));
}
int max(int a,int b) {
    return a>b?a:b;
}
int rob1(int* nums, int numsSize) {
    if(numsSize==0)
        return 0;
    if(numsSize==1)
        return nums[0];
    else if(numsSize==2)
        return nums[0]>nums[1]?nums[0]:nums[1];
    else
    {
        int i;
        int dp1,dp2,dp;

        dp1=nums[0];
        dp2=nums[0]>nums[1]?nums[0]:nums[1];
        for(i=2;i<numsSize;i++)
        {
            dp=dp2>dp1+nums[i]?dp2:dp1+nums[i];
            dp1=dp2;
            dp2=dp;
        }
        return dp;
    }
}

成绩:
1ms,众数100%
Cmershen的碎碎念:
一开始想到对环上每个节点遍历一次,后来发现只讨论第一个节点即可。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

<LeetCode OJ> (198 / 213) House Robber(I / II)

House Robber My Submissions Question Total Accepted: 45702 Total Submissions: 142460 Difficulty:...

[leetcode 213]House Robber II

Note: This is an extension of House Robber. After robbing those houses on that street, the thief ha...

leetcode - 198,213. House Robber(II) & 91. Decode Ways

算法系列博客之Dynamic Programming 本篇博客将运用动态规划的思想来解决leetcode上198和213号问题 问题描述:198 House RobberYou are a pr...
  • Quiteen
  • Quiteen
  • 2017年06月11日 15:09
  • 86

Leetcode 213 House Robber II 抢劫最大金额

HouseRobber扩展:抢劫完那条街道上的房子之后,这个贼有找到了实施自己盗窃行动的另一个地点,这样他才不会引来太多注意。这次,这里的搜有房子排成了一个圆圈,这意味着第一个房子和最后一个房子也是挨...

leetcode 213. House Robber II

After robbing those houses on that street, the thief has found himself a new place for his thievery ...

LeetCode No.213 House Robber II

LeetCode No.213 House Robber II

LeetCode-213. House Robber II

Note: This is an extension of House Robber. After robbing those houses on that street, the thief ha...

LeetCode 213 House Robber II (dp 三种方法 推荐)

LeetCode 213 House Robber II (dp)

LeetCode#213. House Robber II

213. House Robber II Total Accepted: 23996 Total Submissions: 80010 Difficulty: Medium Note: This i...

LeetCode 213. House Robber II 注意考察环尾和环头交叉处

213. House Robber II After robbing those houses on that street, the thief has found himself a new ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目58:213. House Robber II
举报原因:
原因补充:

(最多只允许输入30个字)