Skip to content

Latest commit

 

History

History
85 lines (52 loc) · 2.19 KB

0494-target-sum.adoc

File metadata and controls

85 lines (52 loc) · 2.19 KB

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:
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:

  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.

解题分析

这道题可以使用 DFS 解决。不过,需要注意的是,只需要保存关键变量即可。另外,也可以增加实例变量。

思考题

  1. 再推敲一下动态规划的解法;

  2. 学习背包问题!

参考资料

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:

  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.

link:{sourcedir}/_0494_TargetSum.java[role=include]