Leetcode: 494. Target Sum

Description

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

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.

分析

二分方法:
  输入数组最多长 20, 可以把数组拆为 2 个 长度为 10 的子数组。每个子数组中数字组合出的结果 会有 2**9 个。 将其中一个子数组排序。 然后依次遍历另外一个子数组,通过二分查找有序子数组获取答案。


dp 方法:
  需要思考一下。。。
原文地址:https://www.cnblogs.com/tmortred/p/14436521.html