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.
这是道动态规划的问题。 假设给定的vector为[2,3,4,1,6,5]class Solution { public: int rob(vector<int>& nums) { int length=nums.size(); int *A=new int[length];//A[i] represent the money of rob the room of i and less index. int maxMoney=0; for(int i=0;i<nums.size();i++) { A[i]=0; for(int j=0;j<i-1;j++) { if(A[j]>A[i]) A[i]=A[j]; } A[i]+=nums[i]; if(A[i]>maxMoney) maxMoney=A[i]; } delete [] A; return maxMoney; } };
class Solution { public: int rob(vector<int>& nums) { int length=nums.size(); if(length==0) return 0; if(length==1) return nums[0]; if(length==2) return max(nums[0],nums[1]); int *B=new int[length](); B[0]=nums[0]; B[1]=max(nums[0],nums[1]); for(int i=2;i<length;i++) { B[i]=max(B[i-2]+nums[i],B[i-1]); } return B[length-1]; } };