动态规划法朋友配对问题

给定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
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值