Leetcode::Smallest Sufficient Team

point

Design

Big O(time)

Code

class Solution {
public:
    vector<int> smallestSufficientTeam(vector<string>& req_skills, vector<vector<string>>& people) {
        int n = people.size(), m = req_skills.size();
        map<string, int> skills;
        for(int i = 0; i < m; i++)
            skills[req_skills[i]] = i;
        
        vector<int> personHave(n, 0);
        for(int i = 0; i < n; i++) {
            int skillset = 0;
            for(int j = 0; j < people[i].size(); j++) {
                if (skills.find(people[i][j]) == skills.end()) continue;
                int id = skills[people[i][j]];
                skillset |= (1 << id);
            }
            personHave[i] = skillset;
        }

        vector<long long> DP((1 << m), (1LL << n) - 1);
        DP[0] = 0;

        for (int bitmask = 1; bitmask != (1 << m); bitmask++) {
            for (int i = 0; i < n; i++) {
                int excludingMe = bitmask & ( ~ personHave[i] );
                if (excludingMe == bitmask) continue;

                long long newPeople = DP[excludingMe] | (1LL << i);
                if (__builtin_popcountll(DP[bitmask]) > __builtin_popcountll(newPeople)) {
                    DP[bitmask] = newPeople;
                }
            }
        }

        vector<int> ans;
        int bitmask = (1 << m) - 1;
        long long ppl = DP[bitmask];
        for(int i = 0; i < n; i++) {
            if (ppl & (1LL << i)) {
                ans.push_back(i);
            }
        }
        return ans;
    }
};