Smallest Sufficient Team

In a project, you have a list of required skills req_skills, and a list of people.  The i-th person people[i] contains a list of skills that 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: for example, 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]

 

Constraints:


Solution:

class Solution {
        
    public int[] smallestSufficientTeam(String[] req_skills, List<List<String>> people) {
        List<Integer> p = new ArrayList();
        Map<String, Integer> map = new HashMap();
        for (int i = 0; i < req_skills.length; i ++) {
            map.put(req_skills[i], i);
        }
        int n = req_skills.length;
        Long[] dp = new Long[1 << n];
        dp[0] = (long) 0;
        for (List<String> person : people) {
            int l = 0;
            for (String skill : person) {
                int idx = map.get(skill);
                l |= 1 << idx;
            }
            p.add(l);
        }
        dfs(0, 0, p, dp);
        // for (int i = 0; i < dp.length; i ++) {
        //     if (dp[i] != null) {
        //         System.out.println(Integer.toBinaryString(i) + ", " + Long.toBinaryString(dp[i]));
        //     }
        // };
        List<Integer> res = new ArrayList();
        for (int i = 0; i < people.size(); i ++) {
            if ( ((dp[(1 << n) - 1] >> i) & 1) > 0) {
                res.add(i);
            }
        }
        return res.stream().mapToInt(i -> i).toArray();
    }
    
    private void dfs(int curr, int start, List<Integer> p, Long[] dp) {
        if (start == p.size()) return;
        int skills = p.get(start);
        if (dp[curr | skills] == null || Long.bitCount(dp[curr | skills]) > Long.bitCount(dp[curr]) + 1) {
            dp[curr | skills] = dp[curr] | ((long) 1 << start);
            dfs(curr | skills, start + 1, p, dp);
        }
        dfs(curr, start + 1, p, dp);
    }
}