You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions that you can build, which evaluates to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 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
+1 + 1 + 1 + 1 - 1 = 3
implSolution{#[allow(dead_code)]pubfnfind_target_sum_ways(nums:Vec<i32>,target:i32)->i32{letmutsum=0;forein&nums{sum+=*e;}// -x + (sum - x) = target <-> -2 * x + sum = target <-> 2 * x = sum - targetifsum<target||(sum-target)%2!=0{// There is no way to get any expression in this casereturn0;}letn=nums.len();letm=(sum-target)/2;letmutdp:Vec<Vec<i32>>=vec![vec![0;masusize+1];n+1];// Initialize the dp vectordp[0][0]=1;// Begin the actual dp phaseforiin1..=n{forjin0..=masusize{// nums[i - 1] is not includeddp[i][j]=dp[i-1][j];ifnums[i-1]<=(jasi32){// nums[i - 1] is includeddp[i][j]+=dp[i-1][j-(nums[i-1]asusize)];}}}dp[n][masusize]}}
implSolution{#[allow(dead_code)]pubfnfind_target_sum_ways(nums:Vec<i32>,target:i32)->i32{letmutsum=0;forein&nums{sum+=*e;}ifsum<target||(sum-target)%2!=0{// Just directly returnreturn0;}letn=((sum-target)/2)asusize;letmutdp:Vec<i32>=vec![0;n+1];// Initialize the dp vectordp[0]=1;// Begin the actual dp phaseforein&nums{foriin(*easusize..=n).rev(){dp[i]+=dp[i-(*easusize)];}}dp[n]}}