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.