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.

解题:
可以考虑用动态规划的办法去解题,dp[i] = max(nums[i] + dp[i-2], dp[i-1]);最后dp[size-1]即是要求的结果。可以AC的C++代码如下:

    int rob(vector<int>& nums) {
        int size = nums.size();
        if(size < 1)
           return 0;
        else if(size == 1){
            return nums[0];
        }

        int *dp = new int[size];
        dp[0] = nums[0];
        dp[1] = nums[0] > nums[1] ? nums[0]:nums[1];
        for(int i=2; i<size; i++){
            dp[i] = (nums[i] + dp[i-2]) > dp[i-1] ? (nums[i] + dp[i-2]) : dp[i-1];
        }

        return dp[size - 1];
    }

还有一种解法,核心思想还是用DP,分别维护两个变量a和b, 然后按照奇偶分别来更新a和b。可以AC的C++代码如下:

 int rob(vector<int> &nums) {
 int a = 0, b = 0;
 for (int i = 0; i < nums.size(); ++i) {
            if (i % 2 == 0) {
                a += nums[i];
                a = max(a, b);
            } else {
                b += nums[i];
                b = max(a, b);
            }
        }
        return max(a, b);
    }

精简一下code如下:

      int rob(vector<int> &nums) {
          int size = nums.size();
          if(size < 1)
              return 0;
          else if(size == 1)
              return nums[0];

          int first, second, cur;
          first = nums[0];
          second = nums[1] > nums[0] ? nums[1]:nums[0];
          for(int i=2; i<size; i++){
              cur = (first + nums[i]) > second ? (first + nums[i]) : second;
              first = second;
              second = cur;
          }

          return second;
    }

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