Combination Sum
LeetCode 39 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Recurse with the same index to allow reuse.
मैंने Combination Sum (LeetCode 39) ऐसे हल किया — Combinations पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Each candidate can be reused, so after choosing candidates[i] you recurse starting from i again (not i+1). Stop when the running total hits or passes the target.
Approach
- 1
dfs(start, ds, total): over target → stop; equal → record.
- 2
For i from start: append, dfs(i, …), pop.
मैंने कैसे हल किया
Backtracking with reusePythonexponential
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res=[]
def dfs(start,ds,total):
if total>target:
return
if total==target:
res.append(ds[:])
return
for i in range(start,len(candidates)):
ds.append(candidates[i])
dfs(i,ds,total+candidates[i]) #take duplicate
ds.pop()
dfs(0,[],0)
return resCombination Sum — अक्सर पूछे जाने वाले प्रश्न
Combination Sum के पीछे intuition क्या है?
Each candidate can be reused, so after choosing candidates[i] you recurse starting from i again (not i+1). Stop when the running total hits or passes the target.
Combination Sum (LeetCode 39) कैसे हल करें?
1. dfs(start, ds, total): over target → stop; equal → record. 2. For i from start: append, dfs(i, …), pop.
Combination Sum की time और space complexity क्या है?
Time: O(2^(T/min))। Space: O(T/min)। (Accepted approach: Backtracking with reuse।)
Combination Sum में आम गलतियाँ क्या हैं?
Starting the loop at start (not 0) prevents permutations of the same combination.