- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 39 lines of Java from the credited upstream file 1125.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, cached states.
- 4 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] smallestSufficientTeam(String[] req_skills, List<List<String>> people) {3 final int n = req_skills.length;4 final int nSkills = 1 << n;5 Map<String, Integer> skillToId = new HashMap();6 7 List<Integer>[] dp = new List[nSkills];8 dp[0] = new ArrayList<>();9 10 for (int i = 0; i < req_skills.length; ++i)11 skillToId.put(req_skills[i], i);12 13 for (int i = 0; i < people.size(); ++i) {14 final int currSkill = getSkill(people.get(i), skillToId);15 for (int j = 0; j < nSkills; ++j) {16 if (dp[j] == null)17 continue;18 final int newSkillSet = currSkill | j;19 if (newSkillSet == j) 20 continue;21 if (dp[newSkillSet] == null || dp[newSkillSet].size() > dp[j].size() + 1) {22 dp[newSkillSet] = new ArrayList<>(dp[j]);23 dp[newSkillSet].add(i);24 }25 }26 }27 28 return dp[nSkills - 1].stream().mapToInt(Integer::intValue).toArray();29 }30 31 private int getSkill(List<String> person, Map<String, Integer> skillToId) {32 int mask = 0;33 for (final String skill : person)34 if (skillToId.containsKey(skill))35 mask |= 1 << skillToId.get(skill);36 return mask;37 }38}39