动态规划(斐波那契系列)---强盗抢劫

强盗抢劫

198. House Robber (Easy)

题目描述:

  抢劫一排住户,但是不能抢邻近的住户,求最大抢劫量。

思路分析:

  定义dp数组用来存储最大抢劫量,其中dp[i]表示抢到第i个住户时的最大抢劫量。由于不能抢邻近的住户,如果抢劫了第i-1个住户,那么就不能再抢劫第i个住户,所以 dp[ i ]=max(dp[i-1] , dp[i-2]+nums[ i ])

代码:

public int rob(int []nums){
    int []dp=new int[nums.length+1];
    if(nums==null||nums.length==0)
        return 0;
    dp[0]=0;
    dp[1]=nums[0];
    for(int i=2;i<=nums.length;i++){
        dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i-1]);
    }
    return dp[nums.length];
}

猜你喜欢

转载自www.cnblogs.com/yjxyy/p/11116299.html