← Home

1434. Number of Ways to Wear Different Hats to Each Other

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
143

Let's make this one less mysterious. For 1434. Number of Ways to Wear Different Hats to Each Other, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, backtracking.

The notes already sitting in the source point us in the right direction:

  • TLE
  • 46 / 65 test cases passed.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are backtrack, numberWays, stateCounts.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02//46 / 65 test cases passed.
03class Solution {
04public:
05    vector<bool> used;
06    vector<vector<int>> hats;
07    int count;
08    int MOD = 1e9+7;
09    
10    void backtrack(int s){
11        if(s == hats.size()){
12            count = (count+1)%MOD;
13            // cout << endl;
14            return ;
15        }
16        
17        for(int h : hats[s]){
18            if(used[h]) continue;
19            used[h] = true;
20            // cout << h << " ";
21            backtrack(s+1);
22            used[h] = false;
23        }
24        s++;
25    };
26    
27    int numberWays(vector<vector<int>>& hats) {
28        sort(hats.begin(), hats.end(), 
29            [](const vector<int>& a, const vector<int>& b){
30                return a.size() < b.size();
31            });
32        
33        count = 0;
34        used = vector<bool>(41, false);
35        this->hats = hats;
36        backtrack(0);
37        // cout << endl;
38        return count;
39    }
40};
41
42//DP + Bitmask
43//https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/discuss/608686/C%2B%2B-Bit-masks-and-Bottom-Up-DP
44//Runtime: 32 ms, faster than 100.00% of C++ online submissions for Number of Ways to Wear Different Hats to Each Other.
45//Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Number of Ways to Wear Different Hats to Each Other.
46class Solution {
47public:
48    int numberWays(vector<vector<int>>& hats) {
49        int m = 40; //kinds of hats
50        const int n = hats.size(); //number of people
51        const int MOD = 1e9+7;
52            
53        vector<vector<int>> people(m);
54        
55        //record the counts of each state from 0 to 11...1(n 1s)
56        vector<int> stateCounts(1 << n);
57        /*
58        state 0 means that all people do not wear a hat,
59        and there could only be 1 possible combination of that state 
60        */
61        stateCounts[0] = 1;
62        
63        /*
64        hats[i] lists the hats person i likely to wear
65        */
66        for(int i = 0; i < n; i++){
67            for(int h : hats[i]){
68                //the hat "h" can be worn by person i
69                people[h-1].emplace_back(i);
70            }
71        }
72        
73        for(int h = 0; h < m; h++){
74            // for(int j = 0; j < 1 << n; j++){
75            for(int j = (1 << n)-1; j >= 0; j--){
76                //hat 'h' can be distributed to person 'p'
77                for(int p : people[h]){
78                    //skip the state in which person 'p' already has a hat
79                    /*
80                    the result of (j & (1 << p)) will be 1<<p,
81                    so we can not check with ((j & (1 << p)) == 1)
82                    */
83                    if((j & (1 << p)) != 0) continue;
84                    stateCounts[j | (1 << p)] += stateCounts[j];
85                    stateCounts[j | (1 << p)] %= MOD;
86                }
87            }
88        }
89        
90        return stateCounts[(1<<n)-1];
91    }
92};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.