মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 7 · Backtracking

7.1 Subsets / Permutations / Combinations

চিনবেন কীভাবে
"all subsets/permutations/combinations", "generate all", "every way" — the output itself is exponential, so backtracking is the only way
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: SubsetsLC 78 (Medium — Meta/Amazon High)

Statement (Demo): Given an integer array nums of unique elements, return every possible subset (the power set), with no duplicate subsets. Example: nums=[1,2,3][[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] | ⚡ nums.length ≤ 10

Approach: At each level, take the elements from start onward one by one — every state of the path is a subset. Recurse after taking, pop (undo) on the way back — that push/pop pair is backtracking.

function subsets(nums) {
  const res = [];
  const backtrack = (start, path) => {
    res.push([...path]); // every state is an answer
    for (let i = start; i < nums.length; i++) {
      path.push(nums[i]); // choose
      backtrack(i + 1, path); // explore
      path.pop(); // undo
    }
  };
  backtrack(0, []);
  return res;
}

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

নোট · ফাঁকা

প্রবলেম

  • Permutationsplan · দিন ০৭৩🔥 Must-doLC 46
    (a used[] array, or the swap technique)

    Statement: Given an array nums of distinct integers, return all possible permutations.
    Example: nums=[1,2,3][[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] | ⚡ nums.length ≤ 6

    নোট · ফাঁকা
  • CombinationsLC 77

    Statement: Given integers n and k, return every combination of k numbers chosen from 1..n.
    Example: n=4, k=2[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] | ⚡ 1 ≤ n ≤ 20, 1 ≤ k ≤ n

    নোট · ফাঁকা