Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 216 · Combinations

Combination Sum III

LeetCode 216 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Backtrack over 1..9 with count and sum checks.

मध्यमArrayBacktracking

मी 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. 1

    Candidates 1..9.

  2. 2

    Record when total == n and length == k.

  3. 3

    Stop when total > n.

  4. 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 res
स्टेप-थ्रू लोड होत आहे…

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