Dynamic Programming (DP) with bit masking is a powerful technique used to solve problems that involve dealing with subsets, states, or combinations of items efficiently. It is particularly useful when the problem can be broken down into overlapping subproblems, and the state of the solution can be represented compactly using bits.
Here are scenarios where you should consider using DP with bit masking:
1. Subset or Combination Problems
- When you need to consider all possible subsets or combinations of a set of items.
- Example: Finding the minimum or maximum sum of a subset, or solving the Subset Sum Problem.
# Example: Subset Sum Problem
n = 4
weights = [3, 34, 4, 12]
target = 9
dp = [False] * (target + 1)
dp[0] = True # Empty subset sums to 0
for weight in weights:
for j in range(target, weight - 1, -1):
if dp[j - weight]:
dp[j] = True
print(dp[target]) # True if a subset sums to target
2. State Representation with Multiple Choices
# Example: Count Number of Maximum Bitwise-OR Subsets
def countMaxOrSubsets(nums):
max_or = 0
for num in nums:
max_or |= num
count = 0
for mask in range(1, 1 << len(nums)):
curr_or = 0
for i in range(len(nums)):
if mask & (1 << i):
curr_or |= nums[i]
if curr_or == max_or:
count += 1
return count
3. Problems with Multiple States or Conditions
4. Optimization Problems with Constraints
- When you need to optimize a function under certain constraints, and the constraints can be represented using bits.
- Example: Solving problems like Minimum Cost to Hire K Workers.
5. Graph Problems with Node States
Key Steps to Use DP with Bit Masking:
- Identify the State Representation: Determine what each bit in the mask represents (e.g., inclusion of an item, state of a node, etc.).
- Define the DP Table: Create a DP table where the state is represented by the bitmask.
- Transition Function: Define how to transition from one state to another based on the problem's rules.
- Base Case: Initialize the DP table with base cases (e.g., empty subset, starting state).
- Iterate and Fill the DP Table: Fill the DP table by iterating over all possible states and transitions.
Example: Coin Change Problem with Bit Masking
def coinChange(coins, amount):
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for mask in range(1 << len(coins)):
for i in range(len(coins)):
if mask & (1 << i):
for j in range(coins[i], amount + 1):
dp[j] = min(dp[j], dp[j - coins[i]] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
In summary, use DP with bit masking when the problem involves subsets, combinations, or states that can be efficiently represented using bits, and when the problem can be solved using overlapping subproblems.