Problem 2. 2320. Count Number of Ways to Place Houses
题目描述:
There is a street with n * 2
plots, where there are n
plots on each side of the street. The plots on each side are numbered from 1
to n
. On each plot, a house can be placed.
Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer may be very large, return it modulo 109 + 7
.
Note that if a house is placed on the ith
plot on one side of the street, a house can also be placed on the ith
plot on the other side of the street.
Example 1:
Input: n = 1 Output: 4 Explanation: Possible arrangements: 1. All plots are empty. 2. A house is placed on one side of the street. 3. A house is placed on the other side of the street. 4. Two houses are placed, one on each side of the street.
Example 2:
Input: n = 2 Output: 9 Explanation: The 9 possible arrangements are shown in the diagram above.
Constraints:
1 <= n <= 10^4
解题思路:
这是一道比较简单的动态规划题目。
假设你已经知道了前k个plots的房子的每种情况的布局数量,
现在要增加第k+1个plot的房子,这个时候就基于第k个plot的房型为(0,0)、(0,1)、(1,0)、(1,1)时布局数量去计算即可。
我们能想到这个方案,是因为题目中的条件:不允许两个房子在同一个side相邻。
我们设为第k个plot,两个side分别有和个房子,其中、为0或1,
再设
那么有:
故需要一个2*2*N的dp,其转移公式可以写得清晰一些:
从k=1算到k=n后,再对A(n)求和即可。
于是:
class Solution:
def countHousePlacements(self, n: int) -> int:
mod = 10 ** 9 + 7
def dp(i):
"""return 00,10,01,11"""
if i == 1:
return 1, 1, 1, 1
res = dp(i - 1)
return tuple(map(lambda x: x % mod, (
res[0] + res[1] + res[2] + res[3],
res[0] + res[2],
res[0] + res[1],
res[0]
)))
return sum(dp(n)) % mod