Combination Sum III
LeetCode 216 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Backtrack over 1..9 with count and sum checks.
मैंने Combination Sum III (LeetCode 216) ऐसे हल किया — Combinations पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Choose k distinct digits from 1–9 that add up to n. Backtrack over increasing digits, recording when both the count and the sum match and stopping when the sum overshoots.
Approach
- 1
Candidates 1..9.
- 2
Record when total == n and length == k.
- 3
Stop when total > n.
- 4
Recurse with i+1 so each digit is used once.
मैंने कैसे हल किया
BacktrackingPythonO(C(9,k)) time
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res=[]
candidates=[i+1 for i in range(9)]
def dfs(start,ds,total):
if total==n and len(ds)==k:
res.append(ds[:])
return
if total>n:
return
for i in range(start,len(candidates)):
if i!=start and candidates[i]==candidates[i-1]:
continue
ds.append(candidates[i])
dfs(i+1,ds,total+candidates[i])
ds.pop()
dfs(0,[],0)
return resCombination Sum III — अक्सर पूछे जाने वाले प्रश्न
Combination Sum III के पीछे intuition क्या है?
Choose k distinct digits from 1–9 that add up to n. Backtrack over increasing digits, recording when both the count and the sum match and stopping when the sum overshoots.
Combination Sum III (LeetCode 216) कैसे हल करें?
1. Candidates 1..9. 2. Record when total == n and length == k. 3. Stop when total > n. 4. Recurse with i+1 so each digit is used once.
Combination Sum III की time और space complexity क्या है?
Time: O(C(9, k))। Space: O(k)। (Accepted approach: Backtracking।)
Combination Sum III में आम गलतियाँ क्या हैं?
The duplicate check is harmless here — digits are already unique.