Java

  • import java.util.stream.IntStream;
    
    /**
    
     You are given a list of non-negative integers, a1, a2, ..., an, and a target, S.
     Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
    
     Find out how many ways to assign symbols to make sum of integers equal to target S.
    
     Example 1:
    
     Input: nums is [1, 1, 1, 1, 1], S is 3.
     Output: 5
    
     Explanation:
    
     -1+1+1+1+1 = 3
     +1-1+1+1+1 = 3
     +1+1-1+1+1 = 3
     +1+1+1-1+1 = 3
     +1+1+1+1-1 = 3
    
     There are 5 ways to assign symbols to make the sum of nums be target 3.
     Note:
     The length of the given array is positive and will not exceed 20.
     The sum of elements in the given array will not exceed 1000.
     Your output answer is guaranteed to be fitted in a 32-bit integer.
    
     */
    public class Target_Sum {
    
        public static void main(String[] args) {
            Target_Sum out = new Target_Sum();
            Solution s = out.new Solution();
    
            System.out.println(s.findTargetSumWays(new int[]{1,1,1,1,1}, 3));
        }
    
        class Solution2 {
    
            int res = 0;
            public int findTargetSumWays(int[] nums, int S) {
                dfs(nums, S, 0);
                return res;
            }
    
            void dfs(int[] nums, int S, int cur){
                if(cur == nums.length){
                    if(S == 0)
                        res+=1;
                }else{
                    dfs(nums, S-nums[cur], cur+1);
                    dfs(nums, S+nums[cur], cur+1);
                }
            }
    
        }
    
        class Solution {
    
            int count = 0;
    
            public int findTargetSumWays(int[] nums, int target) {
                dfs(nums, 0, target);
    
                return count;
            }
    
            private void dfs(int[] nums, int i, int target) {
                int sum = IntStream.range(0, i+1).map(p -> nums[p]).sum(); // possible overflow
    
                if (i == nums.length) {
                    if (sum == target) {
                        count++;
                    }
                    return;
                }
    
                dfs(nums, i+1, target);
    
                nums[i] *= (-1); // also overflow
                dfs(nums, i+1, target);
                nums[i] *= (-1);
    
            }
        }
    }
    
  • // OJ: https://leetcode.com/problems/target-sum/
    // Time: O(2^N)
    // Space: O(2^N)
    class Solution {
    public:
        int findTargetSumWays(vector<int>& A, int target) {
            vector<unordered_map<int, int>> memo(A.size());
            function<int(int, int)> dfs = [&](int i, int target) -> int {
                if (i < 0) return target == 0;
                if (memo[i].count(target)) return memo[i][target];
                return memo[i][target] = dfs(i - 1, target + A[i]) + dfs(i - 1, target - A[i]);
            };
            return dfs(A.size() - 1, target);
        }
    };
    
  • class Solution(object):
      def findTargetSumWays(self, nums, S, visited={}, index=0):
        """
        :type nums: List[int]
        :type S: int
        :rtype: int
        """
    
        def helper(nums, S, visited={}, index=0):
          if (index, S) in visited:
            return visited[index, S]
          ans = 0
          if nums:
            ans += helper(nums[1:], S - nums[0], visited, index + 1)
            ans += helper(nums[1:], S + nums[0], visited, index + 1)
          elif S == 0:
            ans += 1
          visited[index, S] = ans
          return ans
    
        return helper(nums, S, {}, 0)
    
    

Java

  • class Solution {
        public int findTargetSumWays(int[] nums, int S) {
            int sum = 0;
            for (int num : nums)
                sum += num;
            int difference = sum - S;
            if (difference < 0 || difference % 2 != 0)
                return 0;
            int maxValue = difference / 2;
            int[] dp = new int[maxValue + 1];
            dp[0] = 1;
            for (int num : nums) {
                for (int i = maxValue; i >= num; i--)
                    dp[i] += dp[i - num];
            }
            return dp[maxValue];
        }
    }
    
  • // OJ: https://leetcode.com/problems/target-sum/
    // Time: O(2^N)
    // Space: O(2^N)
    class Solution {
    public:
        int findTargetSumWays(vector<int>& A, int target) {
            vector<unordered_map<int, int>> memo(A.size());
            function<int(int, int)> dfs = [&](int i, int target) -> int {
                if (i < 0) return target == 0;
                if (memo[i].count(target)) return memo[i][target];
                return memo[i][target] = dfs(i - 1, target + A[i]) + dfs(i - 1, target - A[i]);
            };
            return dfs(A.size() - 1, target);
        }
    };
    
  • class Solution(object):
      def findTargetSumWays(self, nums, S, visited={}, index=0):
        """
        :type nums: List[int]
        :type S: int
        :rtype: int
        """
    
        def helper(nums, S, visited={}, index=0):
          if (index, S) in visited:
            return visited[index, S]
          ans = 0
          if nums:
            ans += helper(nums[1:], S - nums[0], visited, index + 1)
            ans += helper(nums[1:], S + nums[0], visited, index + 1)
          elif S == 0:
            ans += 1
          visited[index, S] = ans
          return ans
    
        return helper(nums, S, {}, 0)
    
    

All Problems

All Solutions