LeetCode 1434: Number of Ways to Wear Different Hats to Each Other

Problem Description

Explanation

To solve this problem, we can use dynamic programming with state compression. The idea is to iterate over all possible mask states (representing which hats are worn by which people) and calculate the number of valid assignments. We can use a 2D DP array where dp[mask][i] represents the number of ways to assign hats to the first i people, with the mask representing the hats chosen by these people. We update the DP array based on the valid assignments and finally return the total number of ways modulo 10^9 + 7.

  • Time complexity: O(n * 2^40)
  • Space complexity: O(2^40)

Solutions

class Solution {
    public int numberWays(List<List<Integer>> hats) {
        int mod = 1000000007;
        int n = hats.size();
        int[][] dp = new int[1 << n][41];
        dp[0][0] = 1;

        List<Integer>[] hList = new ArrayList[41];
        for (int i = 0; i < 41; i++) {
            hList[i] = new ArrayList<>();
        }

        for (int i = 0; i < n; i++) {
            for (int hat : hats.get(i)) {
                hList[hat].add(i);
            }
        }

        for (int mask = 0; mask < (1 << n); mask++) {
            for (int i = 1; i <= 40; i++) {
                for (int j = 0; j < n; j++) {
                    if ((mask & (1 << j)) == 0 && hList[i].contains(j)) {
                        dp[mask | (1 << j)][i] = (dp[mask | (1 << j)][i] + dp[mask][0]) % mod;
                    }
                }
            }

            for (int i = 0; i <= 40; i++) {
                dp[mask][0] = (dp[mask][0] + dp[mask][i]) % mod;
            }
        }

        return dp[(1 << n) - 1][0];
    }
}

Loading editor...