LeetCode 494. Target Sum

作为一个超级小白,最近开始寻找互联网公司的就业机会,可是无奈代码关难过。于是最近开始刷LeetCode上的习题。

这道题其实可以转换为典型的动态规划01背包问题。它的描述如下:

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:

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.

 

首先,要知道这道题的状态转移方程。根据题中的表述可知状态转移方程为:

F(i, v) = F(i-1, v+ci) + F(i-1, v-ci)

其中F(i,v)表示前i个数能组成值为v的组合数,ci为第i个数的值。

 

下面是我的代码解答:

int findTargetSumWays(vector<int>& nums, int S) {
    int numsSum = accumulate(nums.begin(), nums.end(), 0);
    if(S>numsSum||S<-numsSum) return 0;
    int target = S + numsSum;
    vector<int> vec(target+1, 0);
    vec[0] = 1;
    vec[2*nums[0]] += 1;
    int n = nums.size();
    for (int i = 1; i < n; i++){
        for (int j = target; j >=0; j--){
            vec[j] = j - 2 * nums[i] >= 0 ? vec[j] + vec[j - 2 * nums[i]] : vec[j];
        }
    }
    return vec[target];
}

 

posted @ 2018-11-06 08:50  rockalmighty  阅读(177)  评论(0编辑  收藏  举报