494. Target Sum-回溯法、DP。
阿新 • • 發佈:2019-02-20
可以使用方法:回溯法、DP。
問題描述:
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.1)回溯法。
窮舉法,判斷每一種組合是否滿足條件。很容易想象有O(2^n)種組合方式,對於每種組合形式,如果:1、獨立的累加,那麼演算法的最終時間複雜度為O(n*2^n),對應三層for迴圈;2、用一變數記錄,則,最終複雜度為O(2^n),對應兩層for迴圈。
在這使用dfs,時間複雜度為O(2^n),但包含一些剪枝。實際用時310ms。C程式碼:
2)動態規劃dpvoid dfs(int* nums, int numsSize, int Sum, int begin, int S, int* ret){ //Sum:儲存上個狀態的和 begin:下次迴圈的起始index for(int i = begin; i < numsSize; ++i){ int tmp = Sum - 2*nums[i]; if(tmp == S) (*ret)++; if(tmp >= S) dfs(nums, numsSize, tmp, i+1, S, ret);//因為題目中說的是non-negative,包括0,所以得>=而不是>。 } //考慮{ [0,0,0,0,0,0,0,0,1] 1 }例子。 } int findTargetSumWays(int* nums, int numsSize, int S) { int ret = 0, Sum = 0; for(int i = 0; i < numsSize; ++i) Sum += nums[i]; if(Sum == S) ret++; dfs(nums, numsSize, Sum, 0, S, &ret); return ret; }
sum(P) - sum(N) = target
sum(P) + sum(N) + sum(P) - sum(N) = target + sum(P) + sum(N)
2 * sum(P) = target + sum(nums)
所以原問題就轉化成了子陣列和問題(類似的:最大連續子陣列和,和為S的連續正數序列)-----找到一個子集P使得sum(P)
= (target + sum(nums)) / 2。注意,target + sum(nums)必須為偶數。
int subsetSum(int* nums, int numsSize, int target) {
int ret;
int* dp = (int*)malloc((target+1)*sizeof(int));
memset(dp, 0, (target+1)*sizeof(int));
dp[0] = 1;
for(int i = 0; i < numsSize; ++i)
for(int j = target; j >= nums[i]; --j)
dp[j] += dp[j-nums[i]];
ret = dp[target];
free(dp);
return ret;
}
int findTargetSumWays(int* nums, int numsSize, int S) {
int sum = 0, target, ret;
for(int i = 0; i < numsSize; ++i) sum += nums[i];
if(sum < S || (sum + S)%2) return 0;
target = (sum + S)/2;
ret = subsetSum(nums, numsSize, target);
return ret;
}