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.