LeetCode494. Target Sum——01背包

文章目录

一、题目

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
Example 2:

Input: nums = [1], target = 1
Output: 1

Constraints:

1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000

二、题解

class Solution {
   
public:
    int findTargetSumWays(vector<int>& nums, int target) {
   
        int sum = accumulate(nums.begin(),nums.end(),0);
        if(sum < target || ((target & 1) ^ (sum & 1)) == 1) return 0;
        return f(nums,(target + sum) >> 1);
    }
    int f(vector<int>& nums,int t){
   
        if(t < 0) return 0;
        vector<int> dp(t+1,0);
        dp[0] = 1;
        for(auto num:nums){
   
            for(int j = t;j >= num;j--){
   
                dp[j] += dp[j-num];
            }
        }
        return dp[t];
    }
};

相关推荐

  1. LeetCode494. Target Sum——01背包

    2024-02-23 00:56:02       47 阅读
  2. leetcode-动态规划-01背包

    2024-02-23 00:56:02       29 阅读
  3. 01-背包

    2024-02-23 00:56:02       37 阅读
  4. 01背包与完全背包

    2024-02-23 00:56:02       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-23 00:56:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-23 00:56:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-23 00:56:02       87 阅读
  4. Python语言-面向对象

    2024-02-23 00:56:02       96 阅读

热门阅读

  1. Cookie和Session的区别

    2024-02-23 00:56:02       52 阅读
  2. SouthLeetCode-打卡24年02月第3周

    2024-02-23 00:56:02       51 阅读
  3. 【Docker】docker常用命令简介

    2024-02-23 00:56:02       44 阅读
  4. 如何在Python中执行Shell脚本?

    2024-02-23 00:56:02       57 阅读
  5. 深度学习算法工程师面试常见问题及解答

    2024-02-23 00:56:02       58 阅读
  6. P5729 【深基5.例7】工艺品制作

    2024-02-23 00:56:02       51 阅读
  7. 前端项目docker部署

    2024-02-23 00:56:02       56 阅读
  8. 去年面试的运维开发面试题二

    2024-02-23 00:56:02       61 阅读
  9. 【Kuiperinfer】笔记02 GoogleTest入门

    2024-02-23 00:56:02       46 阅读