Count Ways To Assign Unique Cap To Every Person
Last Updated :
13 Nov, 2024
Given n people and 100 types of caps labelled from 1 to 100, along with a 2D integer array caps where caps[i] represents the list of caps preferred by the i-th person, the task is to determine the number of ways the n people can wear different caps.
Example:
Input: caps = [[3, 4], [4, 5], [5]]
Output: 1
Explanation: First person choose cap 3, Second person choose cap 4 and last one cap 5.
Input: caps = [[3, 5, 1], [3, 5]]
Output: 4
Explanation: There are 4 ways to choose hats: (3, 5), (5, 3), (1, 3) and (1, 5)
Using Recursion
In the recursive approach, there are two cases for each cap:
- Skip the current cap, this means we move to the next cap without assigning the current cap to any person, keeping the assigned count unchanged. The recursive call will look like: dfs(assignedCount, cap+1)
- Assign the current cap to each person who prefers it: For each person who likes the current cap, if they do not already have a cap assigned, we assign this cap to them and move to the next cap with the assigned count incremented by 1. After the recursive call, we backtrack by unassigning the cap to explore other possibilities.
The recurrence relation is as follows:
Base Cases:
- If assignedCount == totalPeople, return 1, as this indicates all people have a unique cap assigned.
- If cap > 100, return 0, as this means there are no more caps left to assign but not all people have received a cap.
- dfs(assignedCount, cap) = dfs(assignedCount, cap+1) + ∑person in capToPeople[cap] dfs(assignedCount+1, cap+1) if assignedPeople[person] == false , we loop through each person who prefers the current cap, check if they have already been assigned a cap, and if not, assign it to them and recurse to explore further assignments with the updated assignedCount.
C++
// C++ Code to Assign Unique Cap To Every Person
// using Recursion
#include <bits/stdc++.h>
using namespace std;
// Recursive function to calculate the number of ways
// to assign caps to people such that each person has
// a unique cap
int dfs(int assignedCount, vector<bool>& assignedPeople,
int cap, vector<vector<int>>& capToPeople, int totalPeople) {
// Base case: if all people have a cap assigned, return 1
if (assignedCount == totalPeople) {
return 1;
}
// If we've considered all caps and not everyone
// has a cap, return 0
if (cap > 100) {
return 0;
}
// Case: skip the current cap
int ways = dfs(assignedCount, assignedPeople,
cap + 1, capToPeople, totalPeople);
// Assign the current cap to each person who likes it
for (int person : capToPeople[cap]) {
// Check if the person already has a cap assigned
if (!assignedPeople[person]) {
// Assign current cap to the person
assignedPeople[person] = true;
// Recurse with increased assigned count
ways = ways + dfs(assignedCount + 1, assignedPeople,
cap + 1, capToPeople, totalPeople);
// Backtrack: unassign the cap for other possibilities
assignedPeople[person] = false;
}
}
return ways;
}
// Main function to calculate the number of ways to assign caps
int numberWays(vector<vector<int>>& caps) {
int n = caps.size();
// Map each cap to the list of people who prefer it
vector<vector<int>> capToPeople(101);
for (int i = 0; i < n; ++i) {
for (int cap : caps[i]) {
capToPeople[cap].push_back(i);
}
}
// Initialize assignedPeople vector to track
// assigned caps
vector<bool> assignedPeople(n, false);
// Call the recursive function starting from the first cap
return dfs(0, assignedPeople, 1, capToPeople, n);
}
int main() {
vector<vector<int>> caps
= {{1, 2, 3}, {1, 2}, {3, 4}, {4, 5}};
cout << numberWays(caps) << endl;
return 0;
}
Java
// Java Code to Assign Unique Cap To Every Person
// using Recursion
import java.util.ArrayList;
import java.util.List;
class GfG {
// Recursive function to calculate the number of ways
// to assign caps to people such that each person has
// a unique cap
static int dfs(int assignedCount, ArrayList<Boolean> assignedPeople,
int cap, ArrayList<ArrayList<Integer>> capToPeople, int totalPeople) {
// Base case: if all people have a cap assigned, return 1
if (assignedCount == totalPeople) {
return 1;
}
// If we've considered all caps and not everyone
// has a cap, return 0
if (cap > 100) {
return 0;
}
// Case: skip the current cap
int ways = dfs(assignedCount, assignedPeople,
cap + 1, capToPeople, totalPeople);
// Assign the current cap to each person who likes it
for (int person : capToPeople.get(cap)) {
// Check if the person already has a cap assigned
if (!assignedPeople.get(person)) {
// Assign current cap to the person
assignedPeople.set(person, true);
// Recurse with increased assigned count
ways = ways + dfs(assignedCount + 1, assignedPeople,
cap + 1, capToPeople, totalPeople);
// Backtrack: unassign the cap for other possibilities
assignedPeople.set(person, false);
}
}
return ways;
}
// Main function to calculate the number of ways to assign caps
static int numberWays(ArrayList<ArrayList<Integer>> caps) {
int n = caps.size();
// Map each cap to the list of people who prefer it
ArrayList<ArrayList<Integer>> capToPeople = new ArrayList<>(101);
for (int i = 0; i <= 100; i++) {
capToPeople.add(new ArrayList<>());
}
for (int i = 0; i < n; ++i) {
for (int cap : caps.get(i)) {
capToPeople.get(cap).add(i);
}
}
// Initialize assignedPeople list to track assigned caps
ArrayList<Boolean> assignedPeople = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
assignedPeople.add(false);
}
// Call the recursive function starting from the first cap
return dfs(0, assignedPeople, 1, capToPeople, n);
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> caps = new ArrayList<>();
caps.add(new ArrayList<>(List.of(1, 2, 3)));
caps.add(new ArrayList<>(List.of(1, 2)));
caps.add(new ArrayList<>(List.of(3, 4)));
caps.add(new ArrayList<>(List.of(4, 5)));
System.out.println(numberWays(caps));
}
}
Python
# Python Code to Assign Unique Cap To Every Person
# using Recursion
def dfs(assigned_count, assigned_people, cap, cap_to_people, total_people):
# Base case: if all people have a cap assigned, return 1
if assigned_count == total_people:
return 1
# If we've considered all caps and not everyone
# has a cap, return 0
if cap > 100:
return 0
# Case: skip the current cap
ways = dfs(assigned_count, assigned_people,
cap + 1, cap_to_people, total_people)
# Assign the current cap to each person who likes it
for person in cap_to_people[cap]:
# Check if the person already has a cap assigned
if not assigned_people[person]:
# Assign current cap to the person
assigned_people[person] = True
# Recurse with increased assigned count
ways += dfs(assigned_count + 1, assigned_people,
cap + 1, cap_to_people, total_people)
# Backtrack: unassign the cap for other possibilities
assigned_people[person] = False
return ways
# Main function to calculate the number
# of ways to assign caps
def number_ways(caps):
n = len(caps)
# Map each cap to the list of people who prefer it
cap_to_people = [[] for _ in range(101)]
for i in range(n):
for cap in caps[i]:
cap_to_people[cap].append(i)
# Initialize assigned_people list to track assigned caps
assigned_people = [False] * n
# Call the recursive function starting from the first cap
return dfs(0, assigned_people, 1, cap_to_people, n)
if __name__ == "__main__":
caps = [[1, 2, 3], [1, 2], [3, 4], [4, 5]]
print(number_ways(caps))
C#
// C# Code to Assign Unique Cap To Every Person
// using Recursion
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to calculate the number of ways
// to assign caps to people such that each person has
// a unique cap
static int Dfs(int assignedCount,
bool[] assignedPeople, int cap,
List<List<int>> capToPeople, int totalPeople) {
// Base case: if all people have a cap assigned, return 1
if (assignedCount == totalPeople) {
return 1;
}
// If we've considered all caps and not everyone
// has a cap, return 0
if (cap > 100) {
return 0;
}
// Case: skip the current cap
int ways = Dfs(assignedCount, assignedPeople,
cap + 1, capToPeople, totalPeople);
// Assign the current cap to each person who likes it
foreach (int person in capToPeople[cap]) {
// Check if the person already has a cap assigned
if (!assignedPeople[person]) {
// Assign current cap to the person
assignedPeople[person] = true;
// Recurse with increased assigned count
ways += Dfs(assignedCount + 1, assignedPeople,
cap + 1, capToPeople, totalPeople);
// Backtrack: unassign the cap for other
// possibilities
assignedPeople[person] = false;
}
}
return ways;
}
// Main function to calculate the number of ways
// to assign caps
static int NumberWays(List<List<int>> caps) {
int n = caps.Count;
// Map each cap to the list of people who prefer it
List<List<int>> capToPeople = new List<List<int>>();
for (int i = 0; i <= 100; i++) {
capToPeople.Add(new List<int>());
}
for (int i = 0; i < n; i++) {
foreach (int cap in caps[i]) {
capToPeople[cap].Add(i);
}
}
// Initialize assignedPeople array to
// track assigned caps
bool[] assignedPeople = new bool[n];
// Call the recursive function starting
// from the first cap
return Dfs(0, assignedPeople, 1, capToPeople, n);
}
static void Main() {
List<List<int>> caps = new List<List<int>> {
new List<int> {1, 2, 3},
new List<int> {1, 2},
new List<int> {3, 4},
new List<int> {4, 5}
};
Console.WriteLine(NumberWays(caps));
}
}
JavaScript
// Javascript Code to Assign Unique Cap To Every Person
// using Recursion
function dfs(assignedCount, assignedPeople, cap,
capToPeople, totalPeople) {
// Base case: if all people have a cap assigned, return 1
if (assignedCount === totalPeople) {
return 1;
}
// If we've considered all caps and not everyone
// has a cap, return 0
if (cap > 100) {
return 0;
}
// Case: skip the current cap
let ways = dfs(assignedCount, assignedPeople,
cap + 1, capToPeople, totalPeople);
// Assign the current cap to each person who likes it
for (let person of capToPeople[cap]) {
// Check if the person already has a cap assigned
if (!assignedPeople[person]) {
// Assign current cap to the person
assignedPeople[person] = true;
// Recurse with increased assigned count
ways += dfs(assignedCount + 1,
assignedPeople, cap + 1, capToPeople, totalPeople);
// Backtrack: unassign the cap for other possibilities
assignedPeople[person] = false;
}
}
return ways;
}
// Main function to calculate the number of
// ways to assign caps
function numberWays(caps) {
const n = caps.length;
// Map each cap to the list of people who prefer it
const capToPeople = Array.from({ length: 101 }, () => []);
for (let i = 0; i < n; i++) {
for (let cap of caps[i]) {
capToPeople[cap].push(i);
}
}
// Initialize assignedPeople array to track assigned caps
const assignedPeople = new Array(n).fill(false);
// Call the recursive function starting from the first cap
return dfs(0, assignedPeople, 1, capToPeople, n);
}
const caps = [[1, 2, 3], [1, 2], [3, 4], [4, 5]];
console.log(numberWays(caps));
The above solution will have a exponential time complexity.
Using Top-Down DP (Memoization) - O(n * 2^n) Time and O(2^n) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming.
1. Optimal Substructure: The problem exhibits optimal substructure, meaning that the solution to the problem can be derived from the solutions of smaller subproblems.
The recursive relation is:
- ways = dfs(allMask, assignedPeople, cap+1) (skip current cap)
- ways = ways + dfs(allMask, assignedPeople ∣ (1 << person), cap+1) (assign current cap to a person)
2. Overlapping Subproblems:
Many subproblems are computed multiple times with the same parameters (cap, assignedPeople). To avoid recomputing the same subproblems, we store the result in a memoization table memo[cap][assignedPeople], which stores the number of ways to assign caps for a given cap and assignedPeople combination.
C++
// C++ Code to Assign Unique Cap To Every Person
// using Memoization and Bitmasking
#include <bits/stdc++.h>
using namespace std;
// Recursive function to count ways to assign
// caps with memoization
int dfs(int allMask, int assignedPeople, int cap,
vector<vector<int>>& capToPeople,
vector<vector<int>>& memo) {
// Base case: if all people have hats assigned
if (assignedPeople == allMask) {
return 1;
}
// If we've considered all caps and not everyone
// has a cap, return 0
if (cap > 100) {
return 0;
}
// Return memoized result if already computed
if (memo[cap][assignedPeople] != -1) {
return memo[cap][assignedPeople];
}
// Case: skip the current cap
int ways = dfs(allMask, assignedPeople,
cap + 1, capToPeople, memo);
// Try assigning the current cap to each person
// who can wear it
for (int person : capToPeople[cap]) {
// Check if the person hasn't been assigned a cap yet
if ((assignedPeople & (1 << person)) == 0) {
// Assign current cap to the person
ways = ways + dfs(allMask,
assignedPeople | (1 << person),
cap + 1, capToPeople, memo);
}
}
// Memoize and return the result
return memo[cap][assignedPeople] = ways;
}
// Main function to calculate the number of
// ways to assign caps
int numberWays(vector<vector<int>>& caps) {
int n = caps.size();
int allMask = (1 << n) - 1;
// Create adjacency matrix for
// cap-to-people distribution
vector<vector<int>> capToPeople(101);
for (int i = 0; i < n; ++i) {
for (int cap : caps[i]) {
capToPeople[cap].push_back(i);
}
}
// Memo array to store computed results
vector<vector<int>> memo(101, vector<int>(1 << n, -1));
// Call the recursive function starting
// from the first cap
return dfs(allMask, 0, 1, capToPeople, memo);
}
int main() {
vector<vector<int>> caps
= {{1, 2, 3}, {1, 2}, {3, 4}, {4, 5}};
cout << numberWays(caps) << endl;
return 0;
}
Java
// Java Code to Assign Unique Cap To Every Person
// using Memoization and Bitmasking
import java.util.ArrayList;
import java.util.List;
class GfG {
// Recursive function to calculate the number of ways
// to assign caps to people such that each person has
// a unique cap
static int dfs(int assignedCount, ArrayList<Boolean> assignedPeople,
int cap, ArrayList<ArrayList<Integer>> capToPeople,
int totalPeople) {
// Base case: if all people have a cap assigned, return 1
if (assignedCount == totalPeople) {
return 1;
}
// If we've considered all caps and not everyone
// has a cap, return 0
if (cap > 100) {
return 0;
}
// Case: skip the current cap
int ways = dfs(assignedCount, assignedPeople,
cap + 1, capToPeople, totalPeople);
// Assign the current cap to each person who likes it
for (int person : capToPeople.get(cap)) {
// Check if the person already has a cap assigned
if (!assignedPeople.get(person)) {
// Assign current cap to the person
assignedPeople.set(person, true);
// Recurse with increased assigned count
ways = ways + dfs(assignedCount + 1, assignedPeople,
cap + 1, capToPeople, totalPeople);
// Backtrack: unassign the cap for other possibilities
assignedPeople.set(person, false);
}
}
return ways;
}
// Main function to calculate the number of ways to assign caps
static int numberWays(ArrayList<ArrayList<Integer>> caps) {
int n = caps.size();
// Map each cap to the list of people who prefer it
ArrayList<ArrayList<Integer>> capToPeople = new ArrayList<>(101);
for (int i = 0; i <= 100; i++) {
capToPeople.add(new ArrayList<>());
}
for (int i = 0; i < n; ++i) {
for (int cap : caps.get(i)) {
capToPeople.get(cap).add(i);
}
}
// Initialize assignedPeople list to track assigned caps
ArrayList<Boolean> assignedPeople = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
assignedPeople.add(false);
}
// Call the recursive function starting from the first cap
return dfs(0, assignedPeople, 1, capToPeople, n);
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> caps2 = new ArrayList<>();
caps2.add(new ArrayList<>(List.of(1, 2, 3)));
caps2.add(new ArrayList<>(List.of(1, 2)));
caps2.add(new ArrayList<>(List.of(3, 4)));
caps2.add(new ArrayList<>(List.of(4, 5)));
System.out.println(numberWays(caps2));
}
}
Python
# Python Code to Assign Unique Cap To Every Person
# using Memoization and Bitmasking
# Recursive function to count ways to assign
# caps with memoization
def dfs(all_mask, assigned_people, cap, cap_to_people, memo):
# Base case: if all people have hats assigned
if assigned_people == all_mask:
return 1
# If we've considered all caps and not everyone
# has a cap, return 0
if cap > 100:
return 0
# Return memoized result if already computed
if memo[cap][assigned_people] != -1:
return memo[cap][assigned_people]
# Case: skip the current cap
ways = dfs(all_mask, assigned_people, cap + 1, cap_to_people, memo)
# Try assigning the current cap to each person
# who can wear it
for person in cap_to_people[cap]:
# Check if the person hasn't been assigned a cap yet
if (assigned_people & (1 << person)) == 0:
# Assign current cap to the person
ways += dfs(all_mask, assigned_people | (1 << person),\
cap + 1, cap_to_people, memo)
# Memoize and return the result
memo[cap][assigned_people] = ways
return ways
# Main function to calculate the number of
# ways to assign caps
def number_ways(caps):
n = len(caps)
all_mask = (1 << n) - 1
# Create adjacency matrix for
# cap-to-people distribution
cap_to_people = [[] for _ in range(101)]
for i in range(n):
for cap in caps[i]:
cap_to_people[cap].append(i)
# Memo array to store computed results
memo = [[-1] * (1 << n) for _ in range(101)]
# Call the recursive function starting
# from the first cap
return dfs(all_mask, 0, 1, cap_to_people, memo)
if __name__ == "__main__":
caps = [[1, 2, 3], [1, 2], [3, 4], [4, 5]]
print(number_ways(caps))
C#
// C# Code to Assign Unique Cap To Every Person
// using Memoization and Bitmasking
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to count ways to assign
// caps with memoization
static int dfs(int allMask, int assignedPeople, int cap,
List<List<int>> capToPeople,
List<List<int>> memo) {
// Base case: if all people have hats assigned
if (assignedPeople == allMask) {
return 1;
}
// If we've considered all caps and not everyone
// has a cap, return 0
if (cap > 100) {
return 0;
}
// Return memoized result if already computed
if (memo[cap][assignedPeople] != -1) {
return memo[cap][assignedPeople];
}
// Case: skip the current cap
int ways = dfs(allMask, assignedPeople,
cap + 1, capToPeople, memo);
// Try assigning the current cap to each person
// who can wear it
foreach (int person in capToPeople[cap]) {
// Check if the person hasn't been assigned a cap yet
if ((assignedPeople & (1 << person)) == 0) {
// Assign current cap to the person
ways += dfs(allMask,
assignedPeople | (1 << person),
cap + 1, capToPeople, memo);
}
}
// Memoize and return the result
memo[cap][assignedPeople] = ways;
return ways;
}
// Main function to calculate the number of
// ways to assign caps
static int NumberWays(List<List<int>> caps) {
int n = caps.Count;
int allMask = (1 << n) - 1;
// Create adjacency matrix for
// cap-to-people distribution
List<List<int>> capToPeople
= new List<List<int>>(new List<int>[101]);
for (int i = 0; i < 101; i++) {
capToPeople[i] = new List<int>();
}
for (int i = 0; i < n; i++) {
foreach (int cap in caps[i]) {
capToPeople[cap].Add(i);
}
}
// Memo array to store computed results
List<List<int>> memo
= new List<List<int>>(new List<int>[101]);
for (int i = 0; i < 101; i++) {
memo[i] = new List<int>(new int[1 << n]);
for (int j = 0; j < (1 << n); j++) {
memo[i][j] = -1;
}
}
// Call the recursive function starting
// from the first cap
return dfs(allMask, 0, 1, capToPeople, memo);
}
static void Main(string[] args) {
List<List<int>> caps = new List<List<int>>() {
new List<int>{1, 2, 3},
new List<int>{1, 2},
new List<int>{3, 4},
new List<int>{4, 5}
};
Console.WriteLine(NumberWays(caps));
}
}
JavaScript
// Javascript Code to Assign Unique Cap To Every Person
// using Memoization and Bitmasking
// Recursive function to count ways to assign
// caps with memoization
function dfs(allMask, assignedPeople, cap, capToPeople, memo) {
// Base case: if all people have hats assigned
if (assignedPeople === allMask) {
return 1;
}
// If we've considered all caps and not everyone
// has a cap, return 0
if (cap > 100) {
return 0;
}
// Return memoized result if already computed
if (memo[cap][assignedPeople] !== -1) {
return memo[cap][assignedPeople];
}
// Case: skip the current cap
let ways = dfs(allMask, assignedPeople,
cap + 1, capToPeople, memo);
// Try assigning the current cap to each person
// who can wear it
for (let person of capToPeople[cap]) {
// Check if the person hasn't been assigned a cap yet
if ((assignedPeople & (1 << person)) === 0) {
// Assign current cap to the person
ways += dfs(allMask,
assignedPeople | (1 << person),
cap + 1, capToPeople, memo);
}
}
// Memoize and return the result
memo[cap][assignedPeople] = ways;
return ways;
}
// Main function to calculate the number of
// ways to assign caps
function numberWays(caps) {
let n = caps.length;
let allMask = (1 << n) - 1;
// Create adjacency matrix for
// cap-to-people distribution
let capToPeople = Array.from({ length: 101 }, () => []);
for (let i = 0; i < n; i++) {
for (let cap of caps[i]) {
capToPeople[cap].push(i);
}
}
// Memo array to store computed results
let memo = Array.from({ length: 101 }, () => Array(1 << n).fill(-1));
// Call the recursive function starting
// from the first cap
return dfs(allMask, 0, 1, capToPeople, memo);
}
let caps = [
[1, 2, 3],
[1, 2],
[3, 4],
[4, 5]
];
console.log(numberWays(caps));
Using Bottom-Up DP (Tabulation) – O(n * 2^n) Time and O(2^n) Space
We use a 2D DP table of size (number of caps + 1) * (2^n). The state dp[cap][assignedPeople] represents the number of ways to assign caps to people considering the first cap caps and assigning caps to the people represented by the bitmask assignedPeople.
Dynamic Programming Relation:
Base Case: dp[0][0] = 1, If no caps are assigned and no people are assigned any caps, there is 1 way to do nothing.
Skip the current cap:
- dp[cap][assignedPeople] += dp[cap-1][assignedPeople]
Assign the current cap to a person who hasn't been assigned a cap:
- dp[cap][assignedPeople | (1 << person)] += dp[cap - 1][assignedPeople]
After filling the DP table, the final result will be stored in dp[100][allMask], which represents the number of ways to assign all caps to all people.
C++
// C++ code to calculate the number of ways
// to assign caps to people using Tabulation
#include <bits/stdc++.h>
using namespace std;
int numberWays(vector<vector<int>>& caps) {
int n = caps.size();
int allMask = (1 << n) - 1;
// Create adjacency matrix for cap-to-people distribution
vector<vector<int>> capToPeople(101);
for (int i = 0; i < n; ++i) {
for (int cap : caps[i]) {
capToPeople[cap].push_back(i);
}
}
// DP table: dp[cap][assignedPeople]
// stores the number of ways
// to assign caps for the first 'cap'
// caps with 'assignedPeople' bitmask
vector<vector<int>> dp(102, vector<int>(1 << n, 0));
// Base case: With 0 caps, no people assigned,
// there's 1 way (do nothing)
dp[0][0] = 1;
// Fill the DP table
for (int cap = 1; cap <= 100; ++cap) {
for (int assignedPeople = 0;
assignedPeople <= allMask; ++assignedPeople) {
// If there are no ways to assign caps for
// this state, continue
if (dp[cap - 1][assignedPeople] == 0) {
continue;
}
// Case 1: Skip the current cap
dp[cap][assignedPeople] += dp[cap - 1][assignedPeople];
// Case 2: Assign current cap to each person who can wear it
for (int person : capToPeople[cap]) {
// If the person hasn't been assigned a cap yet
if ((assignedPeople & (1 << person)) == 0) {
dp[cap][assignedPeople | (1 << person)]
+= dp[cap - 1][assignedPeople];
}
}
}
}
// The result will be in dp[100][allMask],
// as we have considered all caps and assigned all people
return dp[100][allMask];
}
int main() {
vector<vector<int>> caps
= {{1, 2, 3}, {1, 2}, {3, 4}, {4, 5}};
cout << numberWays(caps) << endl;
return 0;
}
Java
// Java code to calculate the number of ways
// to assign caps to people using Tabulation
import java.util.*;
class GfG {
// Method to calculate the number of ways
// to assign caps using Tabulation
static int numberWays(List<List<Integer>> caps) {
int n = caps.size();
int allMask = (1 << n) - 1;
// Create adjacency matrix for cap-to-people distribution
List<Integer>[] capToPeople = new ArrayList[101];
for (int i = 0; i < 101; i++) {
capToPeople[i] = new ArrayList<>();
}
// Fill the cap-to-people adjacency list
for (int i = 0; i < n; ++i) {
for (int cap : caps.get(i)) {
capToPeople[cap].add(i);
}
}
// DP table: dp[cap][assignedPeople]
// stores the number of ways to
// assign caps for the first 'cap' caps
// with 'assignedPeople' bitmask
int[][] dp = new int[102][1 << n];
// Base case: With 0 caps, no people assigned,
// there's 1 way (do nothing)
dp[0][0] = 1;
// Fill the DP table
for (int cap = 1; cap <= 100; ++cap) {
for (int assignedPeople = 0;
assignedPeople <= allMask; ++assignedPeople) {
// If there are no ways to assign caps for
// this state, continue
if (dp[cap - 1][assignedPeople] == 0) {
continue;
}
// Case 1: Skip the current cap
dp[cap][assignedPeople] += dp[cap - 1][assignedPeople];
// Case 2: Assign current cap to each person who can wear it
for (int person : capToPeople[cap]) {
// If the person hasn't been assigned a cap yet
if ((assignedPeople & (1 << person)) == 0) {
dp[cap][assignedPeople | (1 << person)]
+= dp[cap - 1][assignedPeople];
}
}
}
}
// The result will be in dp[100][allMask],
// as we have considered all caps and assigned all people
return dp[100][allMask];
}
public static void main(String[] args) {
List<List<Integer>> caps = new ArrayList<>();
caps.add(Arrays.asList(1, 2, 3));
caps.add(Arrays.asList(1, 2));
caps.add(Arrays.asList(3, 4));
caps.add(Arrays.asList(4, 5));
System.out.println(numberWays(caps));
}
}
Python
# Python code to calculate the number of ways
# to assign caps to people using Tabulation
def numberWays(caps):
n = len(caps)
allMask = (1 << n) - 1
# Create adjacency list for cap-to-people
# distribution
capToPeople = [[] for _ in range(101)]
# Fill the cap-to-people adjacency list
for i in range(n):
for cap in caps[i]:
capToPeople[cap].append(i)
# DP table: dp[cap][assignedPeople]
# stores the number of ways to assign
# caps for the first 'cap' caps
# with 'assignedPeople' bitmask
dp = [[0] * (1 << n) for _ in range(102)]
# Base case: With 0 caps, no people assigned,
# there's 1 way (do nothing)
dp[0][0] = 1
# Fill the DP table
for cap in range(1, 101):
for assignedPeople in range(allMask + 1):
# If there are no ways to assign caps for
# this state, continue
if dp[cap - 1][assignedPeople] == 0:
continue
# Case 1: Skip the current cap
dp[cap][assignedPeople] += dp[cap - 1][assignedPeople]
# Case 2: Assign current cap to each person who can wear it
for person in capToPeople[cap]:
# If the person hasn't been assigned a cap yet
if (assignedPeople & (1 << person)) == 0:
dp[cap][assignedPeople | (1 << person)] \
+= dp[cap - 1][assignedPeople]
# The result will be in dp[100][allMask],
# as we have considered all caps and assigned all people
return dp[100][allMask]
if __name__ == "__main__":
caps = [[1, 2, 3], [1, 2], [3, 4], [4, 5]]
print(numberWays(caps))
C#
// C# code to calculate the number of ways
// to assign caps to people using Tabulation
using System;
using System.Collections.Generic;
class GfG {
static int NumberWays(List<List<int>> caps) {
int n = caps.Count;
int allMask = (1 << n) - 1;
// Create adjacency list for cap-to-people
// distribution
List<List<int>> capToPeople
= new List<List<int>>(new List<int>[101]);
for (int i = 0; i < 101; ++i) {
capToPeople[i] = new List<int>();
}
// Fill the cap-to-people adjacency list
for (int i = 0; i < n; ++i) {
foreach (int cap in caps[i]) {
capToPeople[cap].Add(i);
}
}
// DP table: dp[cap][assignedPeople]
// stores the number of ways to assign
// caps for the first 'cap' caps
// with 'assignedPeople' bitmask
int[,] dp = new int[102, 1 << n];
// Base case: With 0 caps, no people assigned,
// there's 1 way (do nothing)
dp[0, 0] = 1;
// Fill the DP table
for (int cap = 1; cap <= 100; ++cap) {
for (int assignedPeople = 0;
assignedPeople <= allMask; ++assignedPeople) {
// If there are no ways to assign caps
// for this state, continue
if (dp[cap - 1, assignedPeople] == 0) {
continue;
}
// Case 1: Skip the current cap
dp[cap, assignedPeople] += dp[cap - 1, assignedPeople];
// Case 2: Assign current cap to each person who can wear it
foreach (int person in capToPeople[cap]) {
// If the person hasn't been assigned a cap yet
if ((assignedPeople & (1 << person)) == 0) {
dp[cap, assignedPeople | (1 << person)]
+= dp[cap - 1, assignedPeople];
}
}
}
}
// The result will be in dp[100, allMask],
// as we have considered all caps and assigned all people
return dp[100, allMask];
}
static void Main() {
List<List<int>> caps = new List<List<int>> {
new List<int> { 1, 2, 3 },
new List<int> { 1, 2 },
new List<int> { 3, 4 },
new List<int> { 4, 5 }
};
Console.WriteLine(NumberWays(caps));
}
}
JavaScript
// JavaScript code to calculate the number of ways
// to assign caps to people using Tabulation
function numberWays(caps) {
const n = caps.length;
const allMask = (1 << n) - 1;
// Create adjacency list for cap-to-people distribution
const capToPeople = Array.from({ length: 101 }, () => []);
// Fill the cap-to-people adjacency list
for (let i = 0; i < n; ++i) {
for (let cap of caps[i]) {
capToPeople[cap].push(i);
}
}
// DP table: dp[cap][assignedPeople]
// stores the number of ways to assign caps
// for the first 'cap' caps with 'assignedPeople' bitmask
const dp = Array.from({ length: 102 }, () => Array(1 << n).fill(0));
// Base case: With 0 caps, no people
// assigned, there's 1 way (do nothing)
dp[0][0] = 1;
// Fill the DP table
for (let cap = 1; cap <= 100; ++cap) {
for (let assignedPeople = 0;
assignedPeople <= allMask; ++assignedPeople) {
// If there are no ways to assign caps
// for this state, continue
if (dp[cap - 1][assignedPeople] === 0) {
continue;
}
// Case 1: Skip the current cap
dp[cap][assignedPeople] += dp[cap - 1][assignedPeople];
// Case 2: Assign current cap to each person who can wear it
for (let person of capToPeople[cap]) {
// If the person hasn't been assigned a cap yet
if ((assignedPeople & (1 << person)) === 0) {
dp[cap][assignedPeople | (1 << person)]
+= dp[cap - 1][assignedPeople];
}
}
}
}
// The result will be in dp[100][allMask],
// as we have considered all caps and assigned all people
return dp[100][allMask];
}
const caps = [
[1, 2, 3],
[1, 2],
[3, 4],
[4, 5]
];
console.log(numberWays(caps));
Similar Reads
Dynamic Programming or DP Dynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
What is Memoization? A Complete Tutorial In this tutorial, we will dive into memoization, a powerful optimization technique that can drastically improve the performance of certain algorithms. Memoization helps by storing the results of expensive function calls and reusing them when the same inputs occur again. This avoids redundant calcula
6 min read
Dynamic Programming (DP) Introduction Dynamic Programming is a commonly used algorithmic technique used to optimize recursive solutions when same subproblems are called again.The core idea behind DP is to store solutions to subproblems so that each is solved only once. To solve DP problems, we first write a recursive solution in a way t
15+ min read
Tabulation vs Memoization Tabulation and memoization are two techniques used to implement dynamic programming. Both techniques are used when there are overlapping subproblems (the same subproblem is executed multiple times). Below is an overview of two approaches.Memoization:Top-down approachStores the results of function ca
9 min read
Optimal Substructure Property in Dynamic Programming | DP-2 The following are the two main properties of a problem that suggest that the given problem can be solved using Dynamic programming: 1) Overlapping Subproblems 2) Optimal Substructure We have already discussed the Overlapping Subproblem property. Let us discuss the Optimal Substructure property here.
3 min read
Overlapping Subproblems Property in Dynamic Programming | DP-1 Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems using recursion and storing the results of subproblems to avoid computing the same results again. Following are the two main properties of a problem that suggests that the given problem
10 min read
Steps to solve a Dynamic Programming Problem Steps to solve a Dynamic programming problem:Identify if it is a Dynamic programming problem.Decide a state expression with the Least parameters.Formulate state and transition relationship.Apply tabulation or memorization.Step 1: How to classify a problem as a Dynamic Programming Problem? Typically,
13 min read
Advanced Topics
Count Ways To Assign Unique Cap To Every PersonGiven n people and 100 types of caps labelled from 1 to 100, along with a 2D integer array caps where caps[i] represents the list of caps preferred by the i-th person, the task is to determine the number of ways the n people can wear different caps.Example:Input: caps = [[3, 4], [4, 5], [5]] Output:
15+ min read
Digit DP | IntroductionPrerequisite : How to solve a Dynamic Programming Problem ?There are many types of problems that ask to count the number of integers 'x' between two integers say 'a' and 'b' such that x satisfies a specific property that can be related to its digits.So, if we say G(x) tells the number of such intege
14 min read
Sum over Subsets | Dynamic ProgrammingPrerequisite: Basic Dynamic Programming, Bitmasks Consider the following problem where we will use Sum over subset Dynamic Programming to solve it. Given an array of 2n integers, we need to calculate function F(x) = ?Ai such that x&i==i for all x. i.e, i is a bitwise subset of x. i will be a bit
10 min read
Easy problems in Dynamic programming
Coin Change - Count Ways to Make SumGiven an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Out
15+ min read
Subset Sum ProblemGiven an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. Examples: Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9.Input: arr[] = [3, 34, 4
15+ min read
Introduction and Dynamic Programming solution to compute nCr%pGiven three numbers n, r and p, compute value of nCr mod p. Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6.We strongly recommend that you click here and practice it, before moving on to the solution.METHOD 1: (Using Dynamic Programming) A Simple Solution is
15+ min read
Rod CuttingGiven a rod of length n inches and an array price[]. price[i] denotes the value of a piece of length i. The task is to determine the maximum value obtainable by cutting up the rod and selling the pieces.Note: price[] is 1-indexed array.Input: price[] = [1, 5, 8, 9, 10, 17, 17, 20]Output: 22Explanati
15+ min read
Painting Fence AlgorithmGiven a fence with n posts and k colors, the task is to find out the number of ways of painting the fence so that not more than two consecutive posts have the same color.Examples:Input: n = 2, k = 4Output: 16Explanation: We have 4 colors and 2 posts.Ways when both posts have same color: 4 Ways when
15 min read
Longest Common Subsequence (LCS)Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
15+ min read
Longest Increasing Subsequence (LIS)Given an array arr[] of size n, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order.Examples: Input: arr[] = [3, 10, 2, 1, 20]Output: 3Explanation: The longest increa
14 min read
Longest subsequence such that difference between adjacents is oneGiven an array arr[] of size n, the task is to find the longest subsequence such that the absolute difference between adjacent elements is 1.Examples: Input: arr[] = [10, 9, 4, 5, 4, 8, 6]Output: 3Explanation: The three possible subsequences of length 3 are [10, 9, 8], [4, 5, 4], and [4, 5, 6], wher
15+ min read
Maximum size square sub-matrix with all 1sGiven a binary matrix mat of size n * m, the task is to find out the maximum length of a side of a square sub-matrix with all 1s.Example:Input: mat = [ [0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0] ]Output: 3Explanation: The maximum length of a
15+ min read
Min Cost PathYou are given a 2D matrix cost[][] of dimensions m à n, where each cell represents the cost of traversing through that position. Your goal is to determine the minimum cost required to reach the bottom-right cell (m-1, n-1) starting from the top-left cell (0,0).The total cost of a path is the sum of
15+ min read
Longest Common Substring (Space optimized DP solution)Given two strings âs1â and âs2â, find the length of the longest common substring. Example: Input: s1 = âGeeksforGeeksâ, s2 = âGeeksQuizâ Output : 5 Explanation:The longest common substring is âGeeksâ and is of length 5.Input: s1 = âabcdxyzâ, s2 = âxyzabcdâ Output : 4Explanation:The longest common su
7 min read
Count ways to reach the nth stair using step 1, 2 or 3A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. The task is to implement a method to count how many possible ways the child can run up the stairs.Examples: Input: 4Output: 7Explanation: There are seven ways: {1, 1, 1, 1}, {1, 2, 1}, {2, 1, 1},
15+ min read
Grid Unique Paths - Count Paths in matrixGiven an matrix of size m x n, the task is to find the count of all unique possible paths from top left to the bottom right with the constraints that from each cell we can either move only to the right or down.Examples: Input: m = 2, n = 2Output: 2Explanation: There are two paths(0, 0) -> (0, 1)
15+ min read
Unique paths in a Grid with ObstaclesGiven a matrix mat[][] of size n * m, where mat[i][j] = 1 indicates an obstacle and mat[i][j] = 0 indicates an empty space. The task is to find the number of unique paths to reach (n-1, m-1) starting from (0, 0). You are allowed to move in the right or downward direction. Note: In the grid, cells ma
15+ min read
Medium problems on Dynamic programming
0/1 Knapsack ProblemGiven n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. Note: The constraint
15+ min read
Printing Items in 0/1 KnapsackGiven weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which repre
12 min read
Unbounded Knapsack (Repetition of items allowed)Given a knapsack weight, say capacity and a set of n items with certain value vali and weight wti, The task is to fill the knapsack in such a way that we can get the maximum profit. This is different from the classical Knapsack problem, here we are allowed to use an unlimited number of instances of
15+ min read
Egg Dropping Puzzle | DP-11You are given n identical eggs and you have access to a k-floored building from 1 to k.There exists a floor f where 0 <= f <= k such that any egg dropped from a floor higher than f will break, and any egg dropped from or below floor f will not break. There are a few rules given below:An egg th
15+ min read
Word BreakGiven a string s and y a dictionary of n words dictionary, check if s can be segmented into a sequence of valid words from the dictionary, separated by spaces.Examples:Input: s = "ilike", dictionary[] = ["i", "like", "gfg"]Output: trueExplanation: The string can be segmented as "i like".Input: s = "
12 min read
Vertex Cover Problem (Dynamic Programming Solution for Tree)A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either âuâ or âvâ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complet
15+ min read
Tile Stacking ProblemGiven integers n (the height of the tower), m (the maximum size of tiles available), and k (the maximum number of times each tile size can be used), the task is to calculate the number of distinct stable towers of height n that can be built. Note:A stable tower consists of exactly n tiles, each stac
15+ min read
Box Stacking ProblemGiven three arrays height[], width[], and length[] of size n, where height[i], width[i], and length[i] represent the dimensions of a box. The task is to create a stack of boxes that is as tall as possible, but we can only stack a box on top of another box if the dimensions of the 2-D base of the low
15+ min read
Partition a Set into Two Subsets of Equal SumGiven an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same.Note: Each element is present in either the first subset or the second subset, but not in both.Examples: Input: arr[] = [1, 5, 11, 5]Output: true Explanation: Th
15+ min read
Travelling Salesman Problem using Dynamic ProgrammingGiven a 2d matrix cost[][] of size n where cost[i][j] denotes the cost of moving from city i to city j. The task is to complete a tour from city 0 (0-based index) to all other cities such that we visit each city exactly once and then at the end come back to city 0 at minimum cost.Note the difference
15 min read
Longest Palindromic Subsequence (LPS)Given a string s, find the length of the Longest Palindromic Subsequence in it. Note: The Longest Palindromic Subsequence (LPS) is the maximum-length subsequence of a given string that is also a Palindrome. Longest Palindromic SubsequenceExamples:Input: s = "bbabcbcab"Output: 7Explanation: Subsequen
15+ min read
Longest Common Increasing Subsequence (LCS + LIS)Given two arrays, a[] and b[], find the length of the longest common increasing subsequence(LCIS). LCIS refers to a subsequence that is present in both arrays and strictly increases.Prerequisites: LCS, LIS.Examples:Input: a[] = [3, 4, 9, 1], b[] = [5, 3, 8, 9, 10, 2, 1]Output: 2Explanation: The long
15+ min read
Find all distinct subset (or subsequence) sums of an arrayGiven an array arr[] of size n, the task is to find a distinct sum that can be generated from the subsets of the given sets and return them in increasing order. It is given that the sum of array elements is small.Examples: Input: arr[] = [1, 2]Output: [0, 1, 2, 3]Explanation: Four distinct sums can
15+ min read
Weighted Job SchedulingGiven a 2D array jobs[][] of order n*3, where each element jobs[i] defines start time, end time, and the profit associated with the job. The task is to find the maximum profit you can take such that there are no two jobs with overlapping time ranges.Note: If the job ends at time X, it is allowed to
15+ min read
Count Derangements (Permutation such that no element appears in its original position)A Derangement is a permutation of n elements, such that no element appears in its original position. For example, a derangement of [0, 1, 2, 3] is [2, 3, 1, 0].Given a number n, find the total number of Derangements of a set of n elements.Examples : Input: n = 2Output: 1Explanation: For two balls [1
12 min read
Minimum insertions to form a palindromeGiven a string s, the task is to find the minimum number of characters to be inserted to convert it to a palindrome.Examples:Input: s = "geeks"Output: 3Explanation: "skgeegks" is a palindromic string, which requires 3 insertions.Input: s= "abcd"Output: 3Explanation: "abcdcba" is a palindromic string
15+ min read
Ways to arrange Balls such that adjacent balls are of different typesThere are 'p' balls of type P, 'q' balls of type Q and 'r' balls of type R. Using the balls we want to create a straight line such that no two balls of the same type are adjacent.Examples : Input: p = 1, q = 1, r = 0Output: 2Explanation: There are only two arrangements PQ and QPInput: p = 1, q = 1,
15+ min read