[leetcode][DP] House Robber

来源:互联网 发布:程序员专业名词 编辑:程序博客网 时间:2024/06/07 20:59

题目:

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.

class Solution {public:    int rob(vector<int>& nums) {if (nums.empty()) return 0;int n = nums.size();//建tablevector<vector<int>> table(n);//table[i][0]表示robber不抢第i家离开第i家时最多能抢到多少钱;table[i][1]表示robber抢第i家离开第i家时最多能抢到多少钱vector<int> one(2);for (int i = 0; i < n; ++i){table[i] = one;}//table初始化one[0] = 0;one[1] = nums[0];table[0] = one;for (int i = 1; i < n; ++i){table[i][0] = table[i - 1][0] > table[i - 1][1] ? table[i - 1][0] : table[i - 1][1];//不抢第i家,第i-1家可能抢也可能不抢,则离开第i家时能抢到的最多钱数是两者中的较大者table[i][1] = nums[i] + table[i - 1][0];//抢第i家,则第i家一定不能抢,则离开第i家时能请到的最多钱数是第i家有的钱数加上不抢第i-1家最多所能抢到的钱数}return table[n - 1][0] > table[n - 1][1] ? table[n - 1][0] : table[n - 1][1];//离开第i家时所能抢到的最多钱数是抢或不抢第i家所能得到的钱数的较大者}};


0 0