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.