900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 动态规划DP 之 抢劫得到最多的财务(只是针对题 别无他意)

动态规划DP 之 抢劫得到最多的财务(只是针对题 别无他意)

时间:2019-12-18 14:09:14

相关推荐

动态规划DP 之 抢劫得到最多的财务(只是针对题 别无他意)

题目描述:

A robber is 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.

1. 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.

2. What if all houses are arranged in a circle?

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.

1. 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.

2. What if all houses are arranged in a circle?

解题思路:

我们假设在这条街上有n家店铺,其中P(i)表示第i家店铺的财务数,而OPT(i)可以表示从抢劫开始到第i家店铺为止所抢劫的财务的总数目。

因此,我们可以知道对于第i家店铺,如果获取其中的财务,则有P(i)+OPT(i-2);如果不获取其中的财务,则有OPT(i-1).故而,为了在第i位置获得最大的财务,即有OPT(i)=max(P(i)+OPT(i-2),OPT(i-1)).

Pseudo-code:

OPT(i) if(i==0) return 0; else if(i==1) return P(1); else return OPT=max(P(i)+OPT(i-2),OPT(i-1)); 在此题中,时间复杂度为T(n)=o(n); 对于第二题,我们知道在环形中,第一个点和最后一个点是相连接的。因此,如果选择了第一个点,肯定不能选择最后一个点。那么,我们就可以将问题分成两种情况来进行讨论:包含第一个点和不包含第一个点,或者说是不包含第一个点和包含最后一个点。最后我们比较这两种情况,并取值最大者。 OPT_CIRCLE_FIRST(i)//即这种情况是选取第一个开始if(i==0) return 0; else if(i==1) return P(1); else return OPT=max(P(i)+OPT(i-2),OPT(i-1));

OPT_CIRCLE_LAST(i)//即选取最后一个if(i==1)//因为第一个是0,则最后一个是1肯定不能选。 return 0; else if(i==2) return P(2);//0和1之间隔着2 else return OPT=max(P(i)+OPT(i-2),OPT(i-1));

OPT_CHOOSEN_BEST(n) FIRST=OPT_CIRCLE_FIRST(n-1);//从第一个开始,则最后一个满足条件的是第n-1个; LAST= OPT_CIRCLE_LAST(n);//结束为最后一个 return max(FIRST,LAST);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。