给定n个朋友,每个人可以保持单身,也可以与其他朋友配对。每个朋友只能配对一次。找出让朋友保持单身或配对的方式总数。
例子 :
Input : n = 3
Output : 4
Explanation
{1}, {2}, {3} : all single
{1}, {2, 3} : 2 and 3 paired but 1 is single.
{1, 2}, {3} : 1 and 2 are paired but 3 is single.
{1, 3}, {2} : 1 and 3 are paired but 2 is single.
Note that {1, 2} and {2, 1} are considered same.
方案
f(n) = ways n people can remain single
or pair up.
For n-th person there are two choices:
1) n-th person remains single, we recur
for f(n - 1)
2) n-th person pairs up with any of the
remaining n - 1 persons. We get (n - 1) * f(n - 2)
Therefore we can recursively write f(n) as:
f(n) = f(n - 1) + (n - 1) * f(n - 2)
由于上述递归公式具有[重叠的子问题],因此可以使用动态编程来解决。
# Python program solution of
# friends pairing problem
# Returns count of ways
# n people can remain
# single or paired up.
def countFriendsPairings(n):
dp = [0 for i in range(n + 1)]
# Filling dp[] in bottom-up manner using
# recursive formula explained above.
for i in range(n + 1):
if(i <= 2):
dp[i] = i
else:
dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]
return dp[n]
# Driver code
n = 1
print(countFriendsPairings(n))
Output :
10