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.