Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 39 · Combinations

Combination Sum

LeetCode 39 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Recurse with the same index to allow reuse.

ಮಧ್ಯಮArrayBacktracking
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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. 1

    dfs(start, ds, total): over target → stop; equal → record.

  2. 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 res
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

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