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.