牌的组合数-python

问:四个人玩牌,去掉大小王,一个人拿牌的组合有多少种可能

方法一:DFS

# 牌的组合数.常识:13*4+2=54 张牌。每一类大小可以拿的张数有:0, 1, 2, 3, 4。问:四个人玩牌,一个人拿牌的组合数有多少种
count = 0
card_num = 0
def num_conbinations():
    dfs(0)
    print(count)
    
def dfs(card_size):
    global count
    global card_num
    # card_size: 牌的点数   card_num: 牌的张数
    if card_size > 13:
        return
    if card_num == 13:
        count += 1
        return
    if card_num > 13:
        return
    for i in range(5):    # 每一类牌有0,1,2,3,4种方式
        card_num += i
        dfs(card_size+1)
        card_num -= i
num_conbinations()

 方法二:dp思想

def find_card_combinations():
    n = 13
    dp = [[0]*(n+1) for _ in range(n+1)]
    for i in range(5):
        dp[1][i] = 1
    for i in range(2, n+1):
        for j in range(n+1):
            dp[i][j] += dp[i-1][j]
            if j >= 1:
                dp[i][j] += dp[i-1][j-1]
                if j >= 2:
                    dp[i][j] += dp[i-1][j-2]
                    if j >= 3:
                        dp[i][j] += dp[i-1][j-3]
                        if j >= 4:
                            dp[i][j] += dp[i-1][j-4]
    print("result: ",dp[n][n])
find_card_combinations()

参考:https://blog.csdn.net/ATFWUS/article/details/104758853

posted @ 2022-08-24 10:02  今夜无风  阅读(91)  评论(0编辑  收藏  举报