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.