LeetCode 494 目标和 Target Sum

博客给出一道题目,要求找出为非负整数列表元素分配 + 或 - 符号,使元素和等于目标值 S 的方案数。题解采用动态规划思想,以空间换时间,避免暴力计算的高复杂度。同时指出解题中的两个小坑,一是更新数组的操作方式,二是首数字为 0 时的初始化问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.

示例

**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.

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

题解

先上代码:

class Solution:
    def findTargetSumWays(self, nums, S):
        summary = sum(nums)
        if S > summary or S < -summary:
            return 0
        dp = [0]*(2*summary+1)
        dp[summary-nums[0]] += 1 
        dp[summary+nums[0]] += 1
        for i in range(1, len(nums)):
            tmp = [0] * (2*summary+1)
            for j in range(2*summary+1):
                if dp[j] != 0:
                    tmp[j + nums[i]] += dp[j]
                    tmp[j - nums[i]] += dp[j]
            dp = list(tmp)
        return dp[S+summary]

说下思路吧:
这道题是动态规划,如果暴力去算的话时间复杂度是 2 n 2^{n} 2n,以动态规划的思想来说呢就是以空间换时间,令dp[i]存放的是前knum进行运算能得到结果i的方案数,那么显然有dp[i+num[k]] = dp[i]dp[i-num[k]] = dp[i],但里面有一个小坑就是得用一个新数组来保存本次更新,而不能直接在原来的数组上操作,因为会造成本次从0变成1的在右边的数当本次遍历过来的时候又做了一次,而实际上这个数字应该下一次才进行运算。另外有个小坑是当第一个数字是0的时候,初始化那里dp[summary-nums[0]] += 1dp[summary+nums[0]] += 1应当是+=而不是=这会造成漏算。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值