Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 40 · Combinations

Combination Sum II

LeetCode 40 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Sort; skip same-level duplicates; break on overshoot.

మధ్యస్థంArrayBacktracking
LeetCode లో తెరవండి ↗

నేను 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. 1

    Sort candidates.

  2. 2

    Equal total → record.

  3. 3

    Skip duplicates (i != start and same as previous).

  4. 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 res
స్టెప్-త్రూ లోడ్ అవుతోంది…

Combination 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.