Leetcode192:house robber

Source: Internet
Author: User

You is a professional robber planning to rob houses along a street. Each house have a certain amount of money stashed, the only constraint stopping all from robbing each of the them are that Adjac ENT houses have security system connected and it'll automatically contact the police if and adjacent houses Wer e broken into on the same night.

This is the problem of the dynamic planning of the Tao.Suppose the given vector is [2,3,4,1,6,5]You can define the state of the DP and the state transition equation in this way:A[0] said that the first 0 households (must rob the No. 0 household) The money is 2. A[1] said that the first 1 households (must rob the 1th household) the money is 3. Because robbed the 1th household, therefore cannot rob No. 0 family. A[2] Represents the a[0]+4 of the money of the first 2 households (must rob the 2nd household). Because robbed the 2nd household, therefore cannot rob 1th family. A[3] said that the first 3 households (must rob the 3rd household) of the money for max{a[0],a[1]}+1. Because robbed the 3rd household, therefore cannot rob 2nd household, can only take a[0],a[1] the maximum value. such a state transfer equation is:A[i]=max{a[j],0}+data[i]. 0<=j<i-1. The largest number of robberies is: Max{a[i]}. 0<=i<nThe code based on this state and state transfer equation is as follows:
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 "the" 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;}    ;

Leetcode192:house robber

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.