Leetcode-198-House Robber

来源:互联网 发布:淘宝客服售后审单视频 编辑:程序博客网 时间:2024/06/08 13:14

题目:

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.

int rob(int* nums, int numsSize) {    int i;    if(numsSize == 0) return 0;    if(numsSize>1 && nums[0]>nums[1]) nums[1] = nums[0];    for(i = 2; i < numsSize; i ++){        nums[i] = (nums[i-2]+nums[i]>nums[i-1])?(nums[i-2]+nums[i]):nums[i-1];    }    return nums[numsSize-1];}


解析:

题目的意思是给一串非负数,求不相邻的数字最大和(题目中说不能获取相邻两个房子的金钱)

这是一道动态规划题目,我们设定每个房子的金钱为m(k)

到第k个房子时能获得的最大金钱数为p(k)=max(p(k-2)+m(k), p(k-1))

p(0)=0, p(1) = m(1), p(2) = max(p(0)+m(2), p(1))=max(m(2), m(1))

0 0
原创粉丝点击