【LeetCode】494. Target Sum 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/target-sum/description/
题目描述
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: 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.
题目大意
给了一个数组和一个target number,现在要给这个数组的每个数添加上+或-, 使得求和的结果是target number。求满足条件的组合个数。
解题方法
动态规划
这个题让我扔了三个月,今天又看了两个小时,动态规划不很懂就是这个后果!
刚开始用的dfs做的,遍历所有的结果,统计满足结果的个数就可以了。没错,超时了。超时的代码如下:
class Solution(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
def helper(index, acc):
if index == len(nums):
if acc == S:
return 1
else:
return 0
return helper(index + 1, acc + nums[index]) + helper(index + 1, acc - nums[index])
return helper(0, 0)
其实一般能用dfs解决的题目,如果题目只要求满足条件的数字而不是所有的结果,那么dfs会超时。解决方法其实基本只有一条路:动态规划。
我们定义了一个二维数组,这个二维数组dp[i][j]的意义是我们从最开始的位置到第i个位置上能够成和为j的组合有多少种,因为求和之后数的范围不确定,所以数组中保存的是字典,字典保存的是到i位置能求得的和为某个数的个数。
所以从左到右进行遍历,在每个位置都把前一个位置的字典拿出来,看前一个位置的所有能求得的和。和当前的数值分别进行加减操作,就能得出新一个位置能求得的和了。
状态转移方程是:
dp[0][0] = 1;
dp[i + 1][x + nums[i]] += dp[i][x];
dp[i + 1][x - nums[i]] += dp[i][x];
注意:其中x是在前一个位置能够成的和。
要注意一点是,dp初始不能采用下面方式:
dp = [collections.defaultdict(int)] * (_len + 1)
这种初始化方式会使每个位置的元素其实是同一个字典。
代码如下:
class Solution:
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
_len = len(nums)
dp = [collections.defaultdict(int) for _ in range(_len + 1)]
dp[0][0] = 1
for i, num in enumerate(nums):
for sum, cnt in dp[i].items():
dp[i + 1][sum + num] += cnt
dp[i + 1][sum - num] += cnt
return dp[_len][S]
这个题的C++代码如下,这里的代码说明了对于unordered_map,在C++里面调用一个不存在的key的时候,会使用默认初始化的版本,类似于Python的collections.defaultdict()。比如这里调用的+=符号,在左侧不存在的时候,会初始化0。
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
const int N = nums.size();
vector<unordered_map<int, int>> dp(N + 1);
dp[0][0] = 1;
for (int i = 0; i < N; i ++) {
for (auto m : dp[i]) {
dp[i + 1][m.first + nums[i]] += m.second;
dp[i + 1][m.first - nums[i]] += m.second;
}
}
return dp[N][S];
}
};
日期
2018 年 5 月 28 日 —— 太阳真的像日光灯~
2018 年 12 月 31 日 —— 2018年最后一天!
【LeetCode】494. Target Sum 解题报告(Python & C++)的更多相关文章
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- LN : leetcode 494 Target Sum
lc 494 Target Sum 494 Target Sum You are given a list of non-negative integers, a1, a2, ..., an, and ...
- [LeetCode] 494. Target Sum 目标和
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symb ...
- Leetcode 494 Target Sum 动态规划 背包+滚动数据
这是一道水题,作为没有货的水货楼主如是说. 题意:已知一个数组nums {a1,a2,a3,.....,an}(其中0<ai <=1000(1<=k<=n, n<=20) ...
- LeetCode: Minimum Path Sum 解题报告
Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to b ...
- 【LeetCode】120. Triangle 解题报告(Python)
[LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...
- LeetCode 2 Add Two Sum 解题报告
LeetCode 2 Add Two Sum 解题报告 LeetCode第二题 Add Two Sum 首先我们看题目要求: You are given two linked lists repres ...
- 【LeetCode】Permutations II 解题报告
[题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...
- 【LeetCode】Island Perimeter 解题报告
[LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...
随机推荐
- Vector总结及部分底层源码分析
Vector总结及部分底层源码分析 1. Vector继承的抽象类和实现的接口 Vector类实现的接口 List接口:里面定义了List集合的基本接口,Vector进行了实现 RandomAcces ...
- day02 Rsyuc备份服务器
day02 Rsyuc备份服务器 一.备份 1.什么是备份 备份就是把重要的数据或者文件复制一份保存到另一个地方,实现不同主机之间的数据同步 一般数据比较重要的情况下,数据如果丢失很容易找不回来了的, ...
- day14 linux三剑客之sed命令
day14 linux三剑客之sed命令 sed命令 Sed 主要用来自动编辑一个或多个文件.简化对文件的反复操作.编写转换程序等. sed(流式编辑器) : sed主要用来修改文件. 1.sed命令 ...
- day31 协程
day31 协程 一.死锁与递归锁 所谓死锁:是指两个或者两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去.此时称系统处于死锁状态或系统产 ...
- REMI源安装php7.3
参考:https://blog.csdn.net/Phplayers/article/details/100901352 php5.6安装参考:https://www.cnblogs.com/Easo ...
- 【leetcode】122.Best Time to Buy and Sell Stock II(股票问题)
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. ...
- 【leetcode】208. Implement Trie (Prefix Tree 字典树)
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently s ...
- Can we access global variable if there is a local variable with same name?
In C, we cannot access a global variable if we have a local variable with same name, but it is possi ...
- 【Linux】【Services】【Package】rpm
CentOS系统上rpm命令管理程序包: 安装.升级.卸载.查询和校验.数据库维护 rpm命令:rpm [OPTIONS] [PACKAGE_F ...
- vueAPI (data,props,methods,watch,computed,template,render)
data Vue 实例的数据对象.Vue 将会递归将 data 的属性转换为 getter/setter,从而让 data 的属性能够响应数据变化.实例创建之后,可以通过vm.$data来访问原始数据 ...