leetcode 494

来源:互联网 发布:linux vim 强制保存 编辑:程序博客网 时间:2024/05/23 00: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 1:

Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5Explanation: -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 = 3There are 5 ways to assign symbols to make the sum of nums be target 3.

Note:

  1. The length of the given array is positive and will not exceed 20.
  2. The sum of elements in the given array will not exceed 1000.
  3. Your output answer is guaranteed to be fitted in a 32-bit integer.

Subscribe to see which companies asked this question.



坑: +0 -0算两次!

1:递归 超时了嘤嘤嘤


class Solution {
public:
    int findTargetSumWays(vector<int> nums, int S) {
        int size = nums.size();
        if (size == 1)
        {
            if(S == nums[0] || S == -1* nums[0])
            {
                if(nums[0] == 0)
                    return 2;
                else
                {
                    //cout<<size << "    " << nums[size-1]<<"    "<<S << endl;
                    return 1;
                }
            }
            else
                return 0;
        }
        int a = nums[size -1];
        
        //cout<<size << "    " << nums[size-1]<<"    "<<S << endl;
        nums.pop_back(); 
        return findTargetSumWays(nums, S - a) + findTargetSumWays(nums, S + a);
        
    }
};


2:考虑到存中间变量,网上解法:

The sum of elements in the given array will not exceed 1000.

所以[2001]数组就可以表示一层,下表为和,值为多少种



class Solution {
public:
    int findTargetSumWays(vector<int> nums, int S) {
        if (S>1000 || S < -1000)
            return 0;
        int* rel = new int [2001];
        int* pre = new int [2001];
        memset(pre, 0, sizeof(rel));
        memset(rel, 0, sizeof(rel));
        //rel[1000] = 1;
        pre[nums[0] + 1000] += 1;
        pre[-1 * nums[0] + 1000] += 1;
        for(int i = 1; i < nums.size() ; i ++)
        {
            for(int j = 0 ; j < 2001; j ++)
            {
                if(pre[j] != 0)
                {
                    rel[j + nums[i]] += pre[j] ;
                    rel[j - nums[i]] += pre[j] ;
                }
            }
            for (int k = 0; k < 2001; k ++)
            {
                pre[k] = rel[k];
                rel[k] = 0;
                //cout << k<<"  "<<rel[k]<<endl;
            }
            //cout<<"--------"<<endl;
            
        }


        return pre[S + 1000];
        
    }
};


0 0