{"type": "session", "harness": "opencode", "id": "cp-10003", "name": "LeetCode 0494: Target Sum"} {"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}} {"type": "message", "message": {"role": "user", "content": "Problem: Target Sum (Difficulty: Medium)\nTags: Array, Dynamic Programming, Backtracking\n\nYou are given an integer array nums and an integer target.\nYou want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.\nReturn the number of different expressions that you can build, which evaluates to target.\n\nExample 1:\nInput: nums = [1,1,1,1,1], target = 3\nOutput: 5\nExplanation: There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3\n\nExample 2:\nInput: nums = [1], target = 1\nOutput: 1\n\nConstraints:\n- 1 <= nums.length <= 20\n- 0 <= nums[i] <= 1000\n- 0 <= sum(nums[i]) <= 1000\n- -1000 <= target <= 1000"}} {"type": "message", "message": {"role": "assistant", "content": "# Time: O(n * S)\n# Space: O(S)\n\nimport collections\n\n\nclass Solution(object):\n def findTargetSumWays(self, nums, S):\n \"\"\"\n :type nums: List[int]\n :type S: int\n :rtype: int\n \"\"\"\n def subsetSum(nums, S):\n dp = collections.defaultdict(int)\n dp[0] = 1\n for n in nums:\n for i in reversed(range(n, S+1)):\n if i-n in dp:\n dp[i] += dp[i-n]\n return dp[S]\n\n total = sum(nums)\n if total < S or (S + total) % 2: return 0\n P = (S + total) // 2\n return subsetSum(nums, P)\n\n"}}