Add to List 198. House Robber

题目:You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

   /*
    解题思路:该题的意思就是不能同时抢劫连续的两家,
             采用动态规划的方式,dp[i]表示抢劫第i的时候,最多能抢劫多少钱
             由于不能连续,所以从dp[i-2]开始遍历,找到最大的dp[j],然后将该
             值与nums[i]相加,即为到的dp[i]的时候,最多能抢劫的金额
    */
    public int rob(int[] nums) {
        if(nums.length==0){
            return 0;
        }
        if(nums.length==1){
            return nums[0];
        }
        int len=nums.length;
        int[] dp=new int[len];//dp[i]表示抢i家的金额
        //初始化,表示只抢一家的情况
        dp[0]=nums[0];
        dp[1]=nums[1];
        int max=dp[0];
        if(max<dp[1]){
            max=dp[1];
        }
        for(int i=2;i<nums.length;i++){
            int temp=0;
            for(int j=i-2;j>=0;j--){
               if(temp<dp[j]){
                  temp=dp[j];
               }
            }//for
            dp[i]=temp+nums[i];
            if(max<dp[i]){
                max=dp[i];
            }
        }//for
        return max;
    }


猜你喜欢

转载自blog.csdn.net/zyilove34/article/details/77955333
今日推荐