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.