Middle-题目58:213. House Robber II

题目原文:
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的碎碎念:
一开始想到对环上每个节点遍历一次,后来发现只讨论第一个节点即可。

你可能感兴趣的:(Middle-题目58:213. House Robber II)