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.