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.