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.