Combination Sum II
LeetCode 40 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Sort; skip same-level duplicates; break on overshoot.
ನಾನು Combination Sum II (LeetCode 40) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Combinations ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Each candidate can be used once, and the input has duplicates. Sort, recurse with i+1, and skip equal values at the same level. Because it's sorted, you can also break as soon as a candidate overshoots the target.
Approach
- 1
Sort candidates.
- 2
Equal total → record.
- 3
Skip duplicates (i != start and same as previous).
- 4
Break if candidate + total > target; else recurse with i+1.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Backtracking with pruningPythonO(2ⁿ) worst case
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
res=[]
candidates.sort()
def dfs(start,ds,total):
if total==target:
res.append(ds[:])
return
for i in range(start,len(candidates)):
if i!=start and candidates[i]==candidates[i-1]:
continue
if candidates[i]+total>target:
break
ds.append(candidates[i])
dfs(i+1,ds,total+candidates[i])
ds.pop()
dfs(0,[],0)
return resCombination Sum II — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Combination Sum II ಹಿಂದಿನ intuition ಏನು?
Each candidate can be used once, and the input has duplicates. Sort, recurse with i+1, and skip equal values at the same level. Because it's sorted, you can also break as soon as a candidate overshoots the target.
Combination Sum II (LeetCode 40) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Sort candidates. 2. Equal total → record. 3. Skip duplicates (i != start and same as previous). 4. Break if candidate + total > target; else recurse with i+1.
Combination Sum II ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(2ⁿ). Space: O(n). (Accepted approach: Backtracking with pruning.)
Combination Sum II ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Break, don't continue — every later candidate is even bigger.