

























In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has.
Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.
team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.
It is guaranteed an answer exists.
Example 1:
Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]] Output: [0,2]
Example 2:
Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]] Output: [1,2]
This is a classic Shortest Path problem on a graph, but because we are dealing with a small number of required skills (up to 16), we can view it as a Dynamic Programming problem with Bitmasking.
We represent the "set of skills" as a binary number (a bitmask).
If the required skills are ["java", "python", "react"], the mask 111 (7 in decimal) represents having all three.
The mask 010 (2 in decimal) represents having only "python".
We want to find the smallest number of people whose combined bitmasks equal the target mask (all skills).
1 class Solution: 2 def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]: 3 n = len(req_skills) 4 # Map skill name to its bit position 5 skill_to_idx = {skill: i for i, skill in enumerate(req_skills)} 6 target_mask = (1 << n) - 1 7 8 # dp[mask] = list of indices of people who cover those skills 9 # Initialize with the empty set for mask 0 10 dp = {0: []} 11 12 for i, person_skills in enumerate(people): 13 # Convert current person's skills into a bitmask 14 current_person_mask = 0 15 for skill in person_skills: 16 if skill in skill_to_idx: 17 current_person_mask |= (1 << skill_to_idx[skill]) 18 19 # Try to combine this person with all skill sets we've found so far 20 # We iterate over a copy of keys to avoid "dictionary changed size during iteration" 21 for mask, team in list(dp.items()): 22 new_mask = mask | current_person_mask 23 24 # If we found a new skill combination OR a shorter way to get an existing one 25 if new_mask not in dp or len(dp[new_mask]) > len(team) + 1: 26 dp[new_mask] = team + [i] 27 28 return dp[target_mask]
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。