Leetcode_198_House Robber
本文是在學習中的總結。歡迎轉載但請注明出處:http://blog.csdn.net/pistolove/article/details/47680663
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.
思路:
(1)這道題非常有意思。在這里就不翻譯成中文了。將題目內容轉化為通俗易懂的形式為:給定一個整數數組Arr,求解數組中連續的不相鄰元素的和的最大值。比如:對于數組中的元素A1,A2,A3,A4。則須要推斷A1+A3,A1+A4,A2+A4中的最大值即為所求。
(2)該題是一道簡單動態規劃相關的題目。假設可以正確地找到當中的遞推關系。那么該題就非常easy了。對于n個數的數組,假設要求得其連續不相鄰元素的最大值,那么我們僅僅需求得n-1個數的最大值,以及求得n-2個數的最大值就可以,這樣就形成了求解該問題的子問題的最大值問題,所以非常easy考慮出遞推關系,假設數組為Arr[],n個數的數組相應的不相鄰連續元素的最大值用函數f(n)表示,則有f(n) = max{f(n-1), f(n-2)+A[n-1]},當中n>=2,f(n)也稱為遞推關系。
當中f(n-1)為n-1個元素的最大值。f(n-2)+Arr[n-1]為n-2個元素的最大值加上數組第n個元素的值,由于要求元素不能相鄰。所以會跳過第n-1個元素。這個應該非常好理解。
對動態規劃感興趣的同學可以看看網上有關動態規劃的文章。個人認為非常有必要學習動態規劃的思想。
(3)詳情見下方代碼。希望本文對你有所幫助。
算法代碼實現例如以下:
package leetcode;/*** * @author liqq**/ public class House_Robber {public static int rob(int[] nums) {if (nums == null || nums.length == 0)return 0;int len = nums.length;int[] rt = new int[len];if (len == 1)return nums[0];if (len == 2) {return nums[0] > nums[1] ? nums[0] : nums[1];}for (int i = 0; i < len; i++) {if (i == 0) {rt[i] = nums[i];} else if (i == 1) {rt[i] = Math.max(rt[i - 1], nums[i]);} else {rt[i] = Math.max(rt[i - 1], rt[i - 2] + nums[i]);}}return rt[len - 1] > rt[len - 2] ? rt[len - 1] : rt[len - 2];} }總結
以上是生活随笔為你收集整理的Leetcode_198_House Robber的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CCAI 2017 中国人工智能大会 6
- 下一篇: 创建回调函数