Press "Enter" to skip to content

Posts tagged as “target”

花花酱 LeetCode 494. Target Sum

题目大意:给你一串数字,你可以在每个数字前放置+或-,问有多少种方法可以使得表达式的值等于target。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:


  1. The length of the given array is positive and will not exceed 20.
  2. The sum of elements in the given array will not exceed 1000.
  3. Your output answer is guaranteed to be fitted in a 32-bit integer.


Idea: DP

Solution 1: DP

Time complexity: O(n*sum)

Space complexity: O(n*sum)


C++ SC O(n)


C++ / V2

Solution 2: DFS

Time complexity: O(2^n)

Space complexity: O(n)



Solution 3: Subset sum

Time complexity: O(n*sum)

Space complexity: O(sum)

C++ w/ copy

C++ w/o copy