Target Sum

Problem

You are given an integer array nums and an integer target.

You 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.

  • For example, if nums = [2, 1], you can add a ’+’ before 2 and a ’-’ before 1 and concatenate them to build the expression “+2-1”.

Return the number of different expressions that you can build, which evaluates to target.

Example 1:

Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 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
+1 + 1 + 1 + 1 - 1 = 3

Example 2:

Input: nums = [1], target = 1
Output: 1

Constraints:

  • 1 <= nums.length <= 20
  • 0 <= nums[i] <= 1000
  • 0 <= sum(nums[i]) <= 1000
  • -1000 <= target <= 1000

Solution

There are better solutions using dynamic programming.

Time: O(2^n) Space: O(n)

class Solution {
    public int findTargetSumWays(int[] nums, int target) {
        return findTargetSumWays(nums, 0, 0, target);
    }

    public int findTargetSumWays(int[] nums, int i, int curr, int target) {
        // base case
        if (i == nums.length) {
            if (curr == target) {
                return 1;
            }
            return 0;
        }

        return findTargetSumWays(nums, i + 1, curr + nums[i], target)
          + findTargetSumWays(nums, i + 1, curr - nums[i], target);
    }
}

Recent posts from blogs that I like

Grit your teeth and ship it

Being good at building and being good at shipping are two separate skills. In the short term, they’re actually countervailing: if you have a gift for building, you’re likely to be worse at shipping. Ira Glass has a classic quote about this.

All of us who do creative work, we get into it because we ...

via Sean Goedecke

Notes on discrete-time Fourier series and transform

The following are my notes on discrete-time Fourier series (DTFS), as well as the discrete-time Fourier transform (DTFT). These topics serve as an important theoretical underpinning to the digital processing of signals by computers using the DFT (which will be covered in a future post). For discrete...

via Eli Bendersky

Painting la Manche: Calais to Étretat

Paintings by JMW Turner, Clarkson Stanfield, Virginie Demont-Breton, Lepic, Boudin, Carpentier, Eugène Isabey, Jongkind, Monet, and others.

via The Eclectic Light Company