【原題】 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.
【分析】
題意就是在每個數(shù)組元素的前面添加正負(fù)號,使得最后的代數(shù)和等于target,求共有多少種解法。
思路一:深度優(yōu)先搜索(DFS)
public class Solution { int ret = 0; public int findTargetSumWays(int[] nums, int S) { if(nums == null || nums.length == 0) return ret; helper(nums,0,0,S); return ret; } public void helper(int[] nums,int index,int sum,int target){ if(index == nums.length){ if(sum==target ) ret++; return ; } helper(nums,index+1,sum+nums[index],target); helper(nums,index+1,sum-nums[index],target); }}思路二:(動態(tài)規(guī)劃)DP 加入“+”和“-”之后原數(shù)組的元素可以看成被分成了兩個子集合,一個正的子集合P,另一個負(fù)的子集合N。 For example:
Given nums = [1, 2, 3, 4, 5] and target = 3 then one possible solution is +1-2+3-4+5 = 3 Here positive subset is P = [1, 3, 5] and negative subset is N = [2, 4]
令sum(P)表示集合P所有元素之和,sum(N)表示集合N所有元素之和
sum(P) - sum(N) = target sum(P) + sum(N) + sum(P) - sum(N) = target + sum(P) + sum(N) 2 * sum(P) = target + sum(nums)
問題轉(zhuǎn)化為求原集合中的一個子集,使得子集所有元素和滿足 sum(P) = (target + sum(nums))/2 【java】
public class Solution { int ret = 0; public int findTargetSumWays(int[] nums, int S) { int sum = 0; for (int n : nums) { sum+=n; } return sum<S || (sum+S)%2>0 ? 0:findSubSet(nums,(sum+S)>>>1); } public int findSubSet(int[] nums, int s) { int[] dp = new int[s+1]; dp[0] = 1;//和為0只有一種 for (int n : nums) { for (int i = s; i >= n; i--) { dp[i] += dp[i-n]; } } return dp[s]; }}新聞熱點
疑難解答