Combinations
LeetCode 77 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Backtrack with a start index; stop at size k.
నేను 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
dfs(index, comb): size k → record.
- 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.