Analysis of C++ dynamic programming classic test questions series

1 Introduction

There are several questions on Likou related to house robbery, which are classic test questions that are often mentioned when learning dynamic programming. They are very representative, and people often see discussions on such questions in communities large and small.

The best way to learn is to summarize, learn from and digest. Based on this purpose, this article also explains such issues, adding personal views on the basis of some excellent ideas.

Let's stop gossip, enter the main text, start 打家劫舍, let's see how much we will gain tonight?

2. Linear Rogue

2.1 Problem Description

A professional burglar, plans to steal and rob houses on the street. There is a certain amount of cash hidden in each room, and you can enter each house. The only constraint that affects the theft is that the adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are burglarized on the same night Intrusion, the system will automatically alarm.

Now given an array of non-negative integers representing the amount stored in each house, calculate the maximum amount you can steal without triggering the alarm device.

Example 1:
Enter:[1,2,3,1]

output:4

Explanation: Steal 1the number house (amount = 1), and then steal 3the number house (amount = 3). Maximum amount stolen = 1+3=4.

Example 2:

enter:[2,7,9,3,1]

output:12

Explanation: Steal 1house No. 3 (money = 2), steal house No. 3 (gold = 9), and then steal house No. 5 (money = 1). The maximum amount stolen = 2+9+1=12.

2.2 Problem Analysis

Don't rush into the room before robbing, you should make an overall estimate first.

Imagine that when a thief starts stealing from the first house, he can choose whether to steal or not. The choice of stealing or not stealing is not due to his instantaneous conscience discovery, but the amount of gain. If there is only one room, he will choose to steal it without hesitation, so as to bring the biggest profit tonight.

The figure below shows the maximum amount a thief can get when there is only one house.

27_0.png

If there are 2houses, what would the thief think when facing the first house?

Profit is important, but if the alarm system is triggered, it is definitely not possible to do a loss-making business such as stealing chickens without losing money. So his idea is to steal, if the benefit from this room is greater than the benefit from another room, otherwise, give up the current room and choose to enter the second room.

28.png

29.png

How do you know whether to steal or not to steal which one will get the most benefits. The only rule is comparison, that is, the benefit of stealing or not stealing is greater. if only

Guess you like

Origin blog.csdn.net/y6123236/article/details/132132329