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.