【LeetCode】House Robber 解题报告
2016-05-01 21:47
288 查看
House Robber
[LeetCode]https://leetcode.com/problems/house-robber/
Total Accepted: 67398 Total Submissions: 196356 Difficulty: Easy
Question
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.
Ways
这种找最大最小值的问题,往往就是利用动态规划!!动态规划的思想:维护一个dp[],每个元素时遍历原数组时能在i处取得的最大值。此处元素应该由状态转移方程决定。
最终要的就是这个状态转移方程。以及dp[]的初始化元素。
这个题目中,在遍历数组的时候,无非就是这么想:这个房子该不该偷?这么决定的因素是这个房子偷了的话的收益和不偷留着偷下一个房子的收益那个比较高?
略微写了个表:
nums: 1 4 2 1 6 4 3 dp: 1 4 4 5 10 10 13
也就是说比较这个房子和前前个dp的值的和与前个dp哪个值更大。
所以:
dp[0] = num[0] (当i=0时)
dp[1] = max(num[0], num[1]) (当i=1时)
dp[i] = max(num[i] + dp[i - 2], dp[i - 1]) (当i !=0 and i != 1时)
public class Solution { public int rob(int[] nums) { if(nums.length==0) return 0; if(nums.length==1) return nums[0]; int[] maxMoney=new int[nums.length]; maxMoney[0]=nums[0]; maxMoney[1]=Math.max(nums[0],nums[1]); for(int i=2; i<nums.length; i++){ maxMoney[i]=Math.max(nums[i]+maxMoney[i-2], maxMoney[i-1]); } return maxMoney[nums.length-1]; } }
AC:0ms
其实可以优化空间复杂度。不优化了。嗯。
Date
2016/5/1 21:44:42相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解