LeetCode 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.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

题目思路

  • 思路一、递归实现,leetcode 超时
class Solution {
public:
    int rob(vector& nums) {
        if(nums.size() == 0){
            return 0;
        }
        
        int a0 = fab(nums, 0);
        int a1 = fab(nums, 1);
        return a0 > a1 ? a0 : a1;
    }
    
    int fab(vector& nums, int k){
        if(k >= nums.size()){
            return 0;
        }
        else{
            int a1 = fab(nums, k+2);
            int a2 = fab(nums, k+3);
            
            int result = a1 > a2 ? a1 : a2;
            return result + nums[k];
        }
    }
};
  • 思路二、看高赞得到的答案,注意初始化从 a=0 开始
class Solution {
public:
    int rob(vector& nums) {
        int len = nums.size();
        
        if(len == 0){
            return 0;
        }
        else if(len == 1){
            return nums[0];
        }
        else if(len == 2){
            return nums[0] > nums[1] ? nums[0] : nums[1];
        }
        else{
            int a = 0;
            int b = nums[0];
            int c = 0;
            for(int i=1; i < len; i++){
                c = nums[i]+a > b ? nums[i]+a : b;
                a = b;
                b = c;
            }
            return c;
        }
    }
};
  • 此代码思路和上述一样,仅仅是 nums.size() 是否用一个变量来代替,就有 4ms 的差距,要注意啊
class Solution {
public:
    int rob(vector& nums) {
        if(nums.size() == 0){
            return 0;
        }
        else if(nums.size() == 1){
            return nums[0];
        }
        else if(nums.size() == 2){
            return nums[0] > nums[1] ? nums[0] : nums[1];
        }
        else{
            int a = 0;
            int b = nums[0];
            int c = 0;
            for(int i=1; i < nums.size(); i++){
                c = nums[i]+a > b ? nums[i]+a : b;
                a = b;
                b = c;
            }
            return c;
        }
    }
};

总结展望

你可能感兴趣的:(LeetCode 198. House Robber)