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.