Tensorum
YouTubeसीखना शुरू करें
LeetCode 77 · Combinations

Combinations

LeetCode 77 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Backtrack with a start index; stop at size k.

मध्यमBacktracking

मैंने Combinations (LeetCode 77) ऐसे हल किया — Combinations पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

Build combinations in increasing order: pick a number, then only consider larger numbers next. When the combination reaches size k, record it.

Approach

  1. 1

    dfs(index, comb): size k → record.

  2. 2

    For i from index to n: append, recurse with i+1, pop.

मैंने कैसे हल किया

BacktrackingPythonO(k·C(n,k)) time
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        res=[]
        def dfs(index,comb):
            if len(comb)==k:
                res.append(comb[:])
                return
            for i in range(index,n+1):
                comb.append(i)
                dfs(i+1,comb)
                comb.pop()
        dfs(1,[])
        return res
स्टेप-थ्रू लोड हो रहा है…

Combinations — अक्सर पूछे जाने वाले प्रश्न

Combinations के पीछे intuition क्या है?

Build combinations in increasing order: pick a number, then only consider larger numbers next. When the combination reaches size k, record it.

Combinations (LeetCode 77) कैसे हल करें?

1. dfs(index, comb): size k → record. 2. For i from index to n: append, recurse with i+1, pop.

Combinations की time और space complexity क्या है?

Time: O(k · C(n, k))। Space: O(k)। (Accepted approach: Backtracking।)

Combinations में आम गलतियाँ क्या हैं?

Pruning when not enough numbers remain (n − i + 1 < k − len) speeds it up.