Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 78 · Subsets

Subsets

LeetCode 78 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Record at every node; extend with later indices.

మధ్యస్థంArrayBacktrackingBit Manipulation
LeetCode లో తెరవండి ↗

నేను 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. 1

    dfs(index, subs) first records a copy of subs.

  2. 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 res
స్టెప్-త్రూ లోడ్ అవుతోంది…

Subsets — తరచూ అడిగే ప్రశ్నలు

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.