494. Target Sum - LeetCode Solution


Dynamic Programming

Python Code:

class Solution:
    def findTargetSumWays(self, arr: List[int], target: int) -> int:

        dppos = []


        for i in range(2001):
            k = []
            for i in range(len(arr) + 1):
                k.append(-1)

            dppos.append(k)






        def trav(s, j):
            if s == target and j == len(arr):
                return 1

            if j == len(arr):
                return 0



            if dppos[s + 1000][j] != -1:
                return dppos[s + 1000][j]
            dppos[s + 1000][j] = 0





            dppos[s + 1000][j]  += trav(s + arr[j], j+1)
            dppos[s + 1000][j] += trav(s - arr[j] , j+1)

            return dppos[s + 1000][j]


        return trav(0, 0)


Comments

Submit
0 Comments
More Questions

1064B - Equations of Mathematical Magic
384A - Coder
1738B - Prefix Sum Addicts
1352D - Alice Bob and Candies
1316D - Nash Matrix
1548B - Integers Have Friends
348A - Mafia
315B - Sereja and Array
204A - Little Elephant and Interval
385B - Bear and Strings
114C - Grammar Lessons
1427A - Avoiding Zero
583A - Asphalting Roads
1358B - Maria Breaks the Self-isolation
828A - Restaurant Tables
1735A - Working Week
1735D - Meta-set
1735B - Tea with Tangerines
1735C - Phase Shift
1321C - Remove Adjacent
281B - Nearest Fraction
1043A - Elections
1598C - Delete Two Elements
1400C - Binary String Reconstruction
1734D - Slime Escape
1499A - Domino on Windowsill
991A - If at first you don't succeed
1196C - Robot Breakout
373A - Collecting Beats is Fun
965A - Paper Airplanes