LeetCode No.416 Partition Equal Subset Sum
来源:互联网 发布:淘宝黑搜任务怎么做 编辑:程序博客网 时间:2024/05/18 14:24
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: trueExplanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]Output: falseExplanation: The array cannot be partitioned into equal sum subsets.
====================================================================================
题目链接:https://leetcode.com/problems/partition-equal-subset-sum/
题目大意:给定一个数组,求该数组能不能分成和相等的两部分。
思路:用动态规划(DP)求解。
题目链接:https://leetcode.com/problems/partition-equal-subset-sum/
题目大意:给定一个数组,求该数组能不能分成和相等的两部分。
思路:用动态规划(DP)求解。
1、先计算数组所有元素之和sum,当和为奇数时肯定不能分成两个和相等的部分
2、half = sum / 2 ,新建一个二维bool数组dp[n][half+1],其中dp[i][j]表示前i个数是否能构成j。
3、初始化dp数组,dp[0][0] = true ,如果nums[0] <= half ,则dp[0][nums[0]] = true
4、dp[i][j] = dp[i][j] || dp[i-1][j-nums[i]]
参考代码:
参考代码:
class Solution {public: bool canPartition(vector<int>& nums) { int n = nums.size() , sum = 0 , maxer = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += nums[i] ; int half = sum >> 1 ; if ( n < 2 || sum % 2 ) return false ; vector < vector <bool> > dp ( n , vector <bool> ( half + 1 , false ) ) ; dp[0][0] = true ; if ( nums[0] <= half ) dp[0][nums[0]] = true ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j <= half ; j ++ ) { dp[i][j] = dp[i][j] || dp[i-1][j] ; if ( j >= nums[i] ) dp[i][j] = dp[i][j] || dp[i-1][j-nums[i]] ; if ( dp[i][half] ) return true ; } } return false ; }};
0 0
- leetCode No.416 Partition Equal Subset Sum
- LeetCode No.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 c++. Partition Equal Subset Sum
- [Leetcode] #416 Partition Equal Subset Sum
- leetcode(416). Partition Equal Subset Sum
- leetcode-416-Partition Equal Subset Sum
- LeetCode: Partition Equal Subset Sum
- LeetCode: Partition Equal Subset Sum
- [LeetCode]Partition Equal Subset Sum
- [LeetCode] Partition Equal Subset Sum
- Leetcode 416 - Partition Equal Subset Sum(dp)
- Leetcode 416 Partition Equal Subset Sum (算法分析week14)
- Leetcode-416. Partition Equal Subset Sum
- LeetCode—416. Partition Equal Subset Sum
- Leetcode 416. Partition Equal Subset Sum
- (17)指针和数组
- 动态规划初步认识之二
- 自定义类型转换
- 欢迎使用CSDN-markdown编辑器
- 洛谷1197星球大战
- LeetCode No.416 Partition Equal Subset Sum
- Eclipse安装反编译插件出错
- Android开发-DesignDemo-AndroidStudio(七)CoordinatorDemo(2)
- python中自定义排序函数
- VB6代码界面滚轮支持
- gcc内嵌汇编
- 自定义标签的实现思路
- MySQL中在查询结果集中得到记录行号的方法
- 提高程序性能、何为缓存——从存储器结构说起