Tensorum
YouTubeसीखना शुरू करें
LeetCode 494 · 0/1 Knapsack / Subset Sum

Target Sum

LeetCode 494 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Count subsets with sum (total + target) / 2 — a 0/1 knapsack count.

मध्यमArrayDynamic ProgrammingBacktrackingKnapsack Problem0-1 Knapsack

मैंने Target Sum (LeetCode 494) ऐसे हल किया — 0/1 Knapsack / Subset Sum पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

Putting + or − in front of each number splits them into a plus group S1 and a minus group S2. Since S1 + S2 = total and S1 − S2 = target, S1 must equal (total + target) / 2. So the question becomes: how many subsets sum to that value?

Approach

  1. 1

    Brute force with memo: dfs(index, curSum) tries + and − for each number.

  2. 2

    Reduce: if total < |target| or (total + target) is odd, there are 0 ways.

  3. 3

    Count subsets summing to tar = (total + target) / 2: exclude or include each number.

  4. 4

    Zeros double the count (with or without them), so the base row gives 2 when nums[0] is 0.

  5. 5

    Final version rolls the table into prev / cur arrays.

मैंने कैसे हल किया · पहले विचार से अंतिम हल तक

1
Memo on (index, sum)O(n·S) time · O(n·S) space

Try + and − for every number.

2
Subset count + memoO(n·tar) time

Reduce to counting subsets that hit tar.

3
Subset count tabulationO(n·tar) time · O(n·tar) space

2-D table of counts.

4
Space-optimised (prev / cur)AcceptedO(n·tar) time · O(tar) space

Two rolling rows.

Memo on (index, sum)PythonO(n·S) time · O(n·S) space
class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        if sum(nums)<abs(target):
            return 0
        memo={}
        def dfs(index,curSum):
            if index==len(nums):
                return 1 if curSum==target else 0
            key=(index, curSum)
            if key in memo:
                return memo[key]
            choice1 = dfs(index+1,curSum+nums[index])
            choice2 = dfs(index+1,curSum-nums[index])
            memo[key]=choice1+choice2
            return memo[key]
        
        return dfs(0,0)
Subset count + memoPythonO(n·tar) time
from functools import lru_cache
class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        totalsum = sum(nums)
        n=len(nums)
        if totalsum<abs(target):
            return 0
        #s1+s2=totalSum
        #s1-s2=targdet
        #s1=(totalSum+target)//2
        if (totalsum+target)%2!=0:
            return 0
        @lru_cache(maxsize=None)
        def countSubsetSumEqualsTarget(index,curTarget):
            if index==0:
                if nums[0]==0 and curTarget==0:
                    return 2 #[0],[]
                if curTarget==0 or nums[0]==curTarget:
                    return 1
                return 0
            exclude = countSubsetSumEqualsTarget(index-1,curTarget)
            include = 0
            if nums[index]<=curTarget:
                 include = countSubsetSumEqualsTarget(index-1,curTarget-nums[index])
            return include+exclude
        tar= (totalsum+target)//2
        return countSubsetSumEqualsTarget(n-1,tar)
Subset count tabulationPythonO(n·tar) time · O(n·tar) space
class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        totalsum = sum(nums)
        n=len(nums)
        if totalsum<abs(target):
            return 0
        #s1+s2=totalSum
        #s1-s2=targdet
        #s1=(totalSum+target)//2
        if (totalsum+target)%2!=0:
            return 0
        
            if index==0:
                if nums[0]==0 and curTarget==0:
                    return 2 #[0],[]
                if curTarget==0 or nums[0]==curTarget:
                    return 1
                return 0
            exclude = countSubsetSumEqualsTarget(index-1,curTarget)
            include = 0
            if nums[index]<=curTarget:
                 include = countSubsetSumEqualsTarget(index-1,curTarget-nums[index])
            return include+exclude
        
        tar= (totalsum+target)//2
        dp=[[0]*(tar+1) for _ in range(n)]
        if nums[0]==0: #[0], target 0
            dp[0][0]=2
        else:
            dp[0][0]=1
            if nums[0]<=tar: #to avoid this case [0], target where 0<=0
                    dp[0][nums[0]]=1
        
        
        for index in range(1,n):
            for curTarget in range(tar+1):
                exclude = dp[index-1][curTarget]
                include = 0
                if nums[index]<=curTarget:
                    include = dp[index-1][curTarget-nums[index]]
                dp[index][curTarget]=include+exclude
        return dp[n-1][tar]
Space-optimised (prev / cur)PythonO(n·tar) time · O(tar) space
class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        totalsum = sum(nums)
        n=len(nums)
        if totalsum<abs(target):
            return 0
        #s1+s2=totalSum
        #s1-s2=targdet
        #s1=(totalSum+target)//2
        if (totalsum+target)%2!=0:
            return 0
        
            if index==0:
                if nums[0]==0 and curTarget==0:
                    return 2 #[0],[]
                if curTarget==0 or nums[0]==curTarget:
                    return 1
                return 0
            exclude = countSubsetSumEqualsTarget(index-1,curTarget)
            include = 0
            if nums[index]<=curTarget:
                 include = countSubsetSumEqualsTarget(index-1,curTarget-nums[index])
            return include+exclude
        
        tar= (totalsum+target)//2
        prev = [0]*(tar+1)
        cur = [0]*(tar+1)
        if nums[0]==0: #[0], target 0
            prev[0]=2
        else:
            prev[0]=1
            if nums[0]<=tar: #to avoid this case [0], target where 0<=0
                    prev[nums[0]]=1
        
        
        for index in range(1,n):
            for curTarget in range(tar+1):
                exclude =prev[curTarget]
                include = 0
                if nums[index]<=curTarget:
                    include = prev[curTarget-nums[index]]
                cur[curTarget]=include+exclude
            prev=cur[:]
        return prev[tar]
स्टेप-थ्रू लोड हो रहा है…

Target Sum — अक्सर पूछे जाने वाले प्रश्न

Target Sum के पीछे intuition क्या है?

Putting + or − in front of each number splits them into a plus group S1 and a minus group S2. Since S1 + S2 = total and S1 − S2 = target, S1 must equal (total + target) / 2. So the question becomes: how many subsets sum to that value?

Target Sum (LeetCode 494) कैसे हल करें?

1. Brute force with memo: dfs(index, curSum) tries + and − for each number. 2. Reduce: if total < |target| or (total + target) is odd, there are 0 ways. 3. Count subsets summing to tar = (total + target) / 2: exclude or include each number. 4. Zeros double the count (with or without them), so the base row gives 2 when nums[0] is 0. 5. Final version rolls the table into prev / cur arrays.

Target Sum की time और space complexity क्या है?

Time: O(n · tar)। Space: O(tar) in the final version। (Accepted approach: Space-optimised (prev / cur)।)

Target Sum में आम गलतियाँ क्या हैं?

Handle nums[0] == 0 in the base case — both [] and [0] reach sum 0. Copy cur into prev (prev = cur[:]) — aliasing them corrupts the next row.

क्या Target Sum को हल करने के एक से ज़्यादा तरीके हैं?

Memo on (index, sum) (O(n·S) time · O(n·S) space): Try + and − for every number. Subset count + memo (O(n·tar) time): Reduce to counting subsets that hit tar. Subset count tabulation (O(n·tar) time · O(n·tar) space): 2-D table of counts. Space-optimised (prev / cur) (O(n·tar) time · O(tar) space): Two rolling rows.