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.