Leetcode 练习:目标和

题目描述:

给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。

返回可以使最终数组和为目标数 S 的所有添加符号的方法数。

示例 1:

输入: nums: [1, 1, 1, 1, 1], S: 3
输出: 5
解释: 

-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

一共有5种方法让最终目标和为3。


注意:


    数组的长度不会超过20,并且数组中的值全为正数。
    初始的数组的和不会超过1000。
    保证返回的最终结果为32位整数。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/target-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

思路:广度优先遍历,每次前进一层,记录当前层的所有结果。最后统计目标数在最后一层中出现的次数即可。

第一次做完发现时间超了,改进方法,将记录每层结果的list改成diction,避免重复计算。

同时发现,尽管题目要求中说了数组中的值全为正数,但是测试用例中仍有含零输入。

 

代码:

class Solution(object):
    def findTargetSumWays(self, nums, S):
        """
        :type nums: List[int]
        :type S: int
        :rtype: int
        """
        if len(nums) == 1:
            if S == nums[0] or S == -nums[0]:
                return 1
            else:
                return 0
        if nums[0] == 0:
            current_level = {0: 2}
        else:
            current_level = {nums[0]: 1, -nums[0]: 1}
        level_count = 0
        while(level_count < len(nums) - 1):
            level_count += 1
            new_level = {}
            for current_value in current_level.keys():
                if current_value + nums[level_count] in new_level:
                    new_level[current_value + nums[level_count]] += current_level[current_value]
                else:
                    new_level[current_value + nums[level_count]] = current_level[current_value]
                if current_value - nums[level_count] in new_level:
                    new_level[current_value - nums[level_count]] += current_level[current_value]
                else:
                    new_level[current_value - nums[level_count]] = current_level[current_value]
            current_level = new_level
        if S in new_level:
            return new_level[S]
        else:
            return 0
        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值