Subsets
LeetCode 78 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Record at every node; extend with later indices.
আমি Subsets (LeetCode 78) এভাবে সমাধান করেছি — Subsets প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Every subset is a sequence of increasing indices. Starting from each index, either stop (record what you have) or extend with a later element and recurse — that enumerates every subset exactly once.
Approach
- 1
dfs(index, subs) first records a copy of subs.
- 2
For i from index onward: append nums[i], recurse with i+1, pop.
আমি কীভাবে সমাধান করেছি
BacktrackingPythonO(n·2ⁿ) time
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res=[]
def dfs(index,subs):
res.append(subs[:])
for i in range(index,len(nums)):
subs.append(nums[i])
dfs(i+1,subs)
subs.pop()
dfs(0,[])
return resSubsets — সাধারণ প্রশ্ন
Subsets-এর পেছনে intuition কী?
Every subset is a sequence of increasing indices. Starting from each index, either stop (record what you have) or extend with a later element and recurse — that enumerates every subset exactly once.
Subsets (LeetCode 78) কীভাবে সমাধান করবেন?
1. dfs(index, subs) first records a copy of subs. 2. For i from index onward: append nums[i], recurse with i+1, pop.
Subsets-এর time আর space complexity কত?
Time: O(n · 2ⁿ)। Space: O(n) recursion। (Accepted approach: Backtracking।)
Subsets-এ সাধারণ ভুলগুলো কী?
Record a copy (subs[:]) — the list keeps changing.