国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

leetcode[494]:Target Sum

2019-11-08 03:19:22
字體:
供稿:網(wǎng)友

【原題】 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]; }}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 同江市| 张家川| 麟游县| 泾阳县| 靖安县| 黎川县| 交城县| 和硕县| 新巴尔虎左旗| 孟连| 报价| 葫芦岛市| 潼关县| 东源县| 天水市| 贡嘎县| 蒙山县| 乐昌市| 汾阳市| 文化| 博客| 梨树县| 东港市| 莱西市| 安宁市| 香格里拉县| 沙坪坝区| 清水河县| 固原市| 邢台县| 佛学| 广宁县| 五寨县| 永德县| 武穴市| 太谷县| 松阳县| 津市市| 成都市| 衢州市| 嘉善县|