LeetCode 494. Target Sum
题目描述:
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
2
3
4
5
6
7
8
9
10
11
12 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.
暴力的DFS可以AC,但是Runtime不理想.
1 | class Solution { |
使用DP是比较好的选择。dp[i][j]
表示前i+1
个元素中和为j
的情况数,由于和可能为负,所以为了确保下标非负,所有的j
减去所有元素的和sum
后才是真正的和。
要注意在初始化时,第一个元素如果为0,那么和0所对应的下标sum
应该初始化为2而不是1。
1 | class Solution { |