leetcode 416. Partition Equal Subset Sum 动态规划DP + DFS深度优先遍历
来源:互联网 发布:网络电视怎么搜索频道 编辑:程序博客网 时间:2024/05/05 15:45
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
这道题可以使用DFS来做,但是可能超时,我想到了使用DP动态规划,但是忘记又该怎么做了,这道题又一次给了一个警醒,DP动态规划真的是很难得,不过本题还是很简单了的dp[i]表示和为i是否可以被满足
本题建议和leetcode 698. Partition to K Equal Sum Subsets K个子集 + 深度优先搜索DFS 一起学习
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>using namespace std;class Solution {public: bool canPartition(vector<int>& nums) { int sum = 0; for (int a : nums) sum += a; if (sum % 2 != 0) return false; int target = sum / 2; vector<bool>dp (target + 1, 0); dp[0] = true; for (int i = 0; i < nums.size(); i++) { for (int j = target; j>= nums[i]; j--) dp[j] = dp[j]|| dp[j-nums[i]]; } return dp[target]; }};
阅读全文
0 0
- leetcode 416. Partition Equal Subset Sum 动态规划DP + DFS深度优先遍历
- 动态规划-416. Partition Equal Subset Sum
- leetcode 377. Combination Sum IV 组合之和 + DP动态规划 + DFS深度优先遍历
- leetcode 494. Target Sum 深度优先遍历DFS + DP动态规划
- 416. Partition Equal Subset Sum 类别:动态规划 难度:medium
- 416. Partition Equal Subset Sum (dp)
- Leetcode-416. Partition Equal Subset Sum
- LeetCode—416. Partition Equal Subset Sum
- Leetcode 416. Partition Equal Subset Sum
- 【leetcode】416. Partition Equal Subset Sum
- 【LeetCode】416. Partition Equal Subset Sum
- 【LeetCode】416. Partition Equal Subset Sum
- LeetCode 416. Partition Equal Subset Sum
- 【LeetCode】416. Partition Equal Subset Sum
- Leetcode 416. Partition Equal Subset Sum[medium]
- [LeetCode]416. Partition Equal Subset Sum
- 【LeetCode】 416. Partition Equal Subset Sum
- Leetcode 416. Partition Equal Subset Sum
- oracle一个中文占几个字节?
- Python对数据shape的常见操作总结
- 使用git命令从本地上传项目至码云
- KDTable监听事件
- 基数估计算法(二):Linear Counting算法
- leetcode 416. Partition Equal Subset Sum 动态规划DP + DFS深度优先遍历
- CSS3选择器
- 教你一步步集成友盟推送(UPUSH)
- XAMPP Mysql/MariaDB 忘记密码
- 斐波那契数列递归与非递归的实现
- 获取某个月的第一天和最后一天
- 引用数据类型之String(一)
- 【Scikit-Learn 中文文档】随机梯度下降
- ArrayList数组变成字符串