Target Sum
LeetCode 494 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Count subsets with sum (total + target) / 2 — a 0/1 knapsack count.
আমি 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
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.
আমি কীভাবে সমাধান করেছি · প্রথম ভাবনা থেকে চূড়ান্ত সমাধান
Try + and − for every number.
Reduce to counting subsets that hit tar.
2-D table of counts.
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.