মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 9 · Dynamic Programming

9.11 Bitmask / Digit DP

চিনবেন কীভাবে
Bitmask: N ≤ 20 and the state is "which elements are used" — turn the subset into an integer. Digit DP: "how many numbers up to X have digit property Y" — count digit by digit
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Partition to K Equal Sum SubsetsLC 698 (Medium — Meta/LinkedIn High)

Statement (Demo): Given an integer array nums and an integer k, return whether it can be divided into k non-empty subsets with equal sums. Example: nums=[4,3,2,3,5,2,1], k=4true ([5], [1,4], [2,3], [2,3] — each sums to 5) | ⚡ nums.length ≤ 16

Approach: mask = which elements are already used. When the current bucket fills (curSum % target === 0), a new bucket starts. Memoize the result per mask — that turns exponential search into O(2ⁿ · n).

function canPartitionKSubsets(nums, k) {
  const total = nums.reduce((a, b) => a + b, 0);
  if (total % k) return false;
  const target = total / k;
  nums.sort((a, b) => b - a);
  if (nums[0] > target) return false;
  const n = nums.length;
  const memo = new Map();
  const dfs = (mask, curSum) => {
    if (mask === (1 << n) - 1) return true; // every element used
    if (memo.has(mask)) return memo.get(mask);
    let ok = false;
    for (let i = 0; i < n && !ok; i++) {
      if (mask & (1 << i)) continue;
      if (curSum + nums[i] <= target)
        ok = dfs(mask | (1 << i), (curSum + nums[i]) % target);
    }
    memo.set(mask, ok);
    return ok;
  };
  return dfs(0, 0);
}

Complexity: Time O(2ⁿ · n), Space O(2ⁿ)

Demo · Partition to K Equal Sum Subsetsplan · দিন ১০৩LC 698
নোট · ফাঁকা

প্রবলেম

  • Numbers At Most N Given Digit SetLC 902
    (entry point to digit DP)

    Statement: Given a sorted set of digits (each may be reused) and an integer n, return how many positive integers made only of those digits are ≤ n.
    Example: digits=["1","3","5","7"], n=10020 | ⚡ digits.length ≤ 9, n ≤ 10⁹

    নোট · ফাঁকা