494. Target Sum-回溯法、DP。

可以使用方法:回溯法、DP。

相近的问题:Partition Equal Subset Sum01背包(1)01背包(2)

问题描述:

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代码:

void 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;
}

2)动态规划dp

这里参见讨论:https://discuss.leetcode.com/topic/76243/java-15-ms-c-3-ms-o-ns-iterative-dp-solution-using-subset-sum-with-explanation

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)必须为偶数。

而关于子数组和问题,可见:Partition Equal Subset Sum,以及对应的dp解法:http://blog.csdn.net/u011567017/article/details/55057394

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;
}



    原文作者:回溯法
    原文地址: https://blog.csdn.net/u011567017/article/details/55054999
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞