问题描述

在一副牌中,你需要找出包含给定数量的某种牌面的牌的组合数。一副牌有52张牌,每种牌面有4张。

示例 1: 输入: cards = [1,2,3,4,4,3,2,1], k = 4, w = 2 输出: 10 解释: 有10种包含每种牌面各2张的组合,例如: [1,1,1,1,2,2,2,2], [1,1,1,1,3,3,3,3], [1,1,1,1,4,4,4,4], [2,2,2,2,3,3,3,3], [2,2,2,2,4,4,4,4], [3,3,3,3,4,4,4,4], [1,1,1,2,2,2,3,3], [1,1,1,3,3,3,2,2], [1,1,1,4,4,4,2,2], [1,1,1,4,4,4,3,3]。

示例 2: 输入: cards = [1,1,1,2,2,2,3,3], k = 2, w = 3 输出: 6 解释: 有6种包含每种牌面各3张,另一种牌面2张的组合,例如: [1,1,1,2,2,2,3,3], [1,1,1,3,3,2,2,2], [1,1,1,3,3,3,2,2], [1,1,1,2,2,3,3,2], [1,1,1,2,2,3,2,3], [1,1,1,3,2,2,2,3]。

解法一

解题思路: 使用组合数学中的公式来解决这个问题。我们需要找出所有可能的组合,其中每种牌面的数量满足条件。

/** @lc app=leetcode.cn id=914 lang=javascript** [914] X of a Kind in a Deck of Cards*/// @lc code=start
function deckCombinations(cards, k, w) {let count = 0;let freq = {};for (let card of cards) {freq[card] = (freq[card] || 0) + 1;}let keys = Object.keys(freq);let dfs = (index, used) => {if (used.length === w) {count++;return;}for (let i = index; i < keys.length; i++) {let key = keys[i];let need = Math.min(freq[key], Math.floor((w - used.length) / k));for (let j = 1; j <= need; j++) {used.push(key);dfs(i, used);used.pop();}}};dfs(0, []);return count;
}
// @lc code=end