|
| 1 | +/** |
| 2 | + * 1125. Smallest Sufficient Team |
| 3 | + * https://leetcode.com/problems/smallest-sufficient-team/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * In a project, you have a list of required skills reqSkills, and a list of people. The ith |
| 7 | + * person people[i] contains a list of skills that the person has. |
| 8 | + * |
| 9 | + * Consider a sufficient team: a set of people such that for every required skill in reqSkills, |
| 10 | + * there is at least one person in the team who has that skill. We can represent these teams by |
| 11 | + * the index of each person. |
| 12 | + * |
| 13 | + * For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and |
| 14 | + * people[3]. |
| 15 | + * |
| 16 | + * Return any sufficient team of the smallest possible size, represented by the index of each |
| 17 | + * person. You may return the answer in any order. |
| 18 | + * |
| 19 | + * It is guaranteed an answer exists. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {string[]} reqSkills |
| 24 | + * @param {string[][]} people |
| 25 | + * @return {number[]} |
| 26 | + */ |
| 27 | +var smallestSufficientTeam = function(reqSkills, people) { |
| 28 | + const skillCount = reqSkills.length; |
| 29 | + const skillMap = new Map(reqSkills.map((skill, index) => [skill, 1 << index])); |
| 30 | + const peopleSkills = people.map(skills => |
| 31 | + skills.reduce((mask, skill) => mask | skillMap.get(skill), 0) |
| 32 | + ); |
| 33 | + const target = (1 << skillCount) - 1; |
| 34 | + const dp = new Map([[0, []]]); |
| 35 | + |
| 36 | + for (let i = 0; i < people.length; i++) { |
| 37 | + const currentSkill = peopleSkills[i]; |
| 38 | + for (const [prevMask, team] of dp) { |
| 39 | + const newMask = prevMask | currentSkill; |
| 40 | + if (!dp.has(newMask) || dp.get(newMask).length > team.length + 1) { |
| 41 | + dp.set(newMask, [...team, i]); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return dp.get(target); |
| 47 | +}; |
0 commit comments