leetCode No.416 Partition Equal Subset Sum
来源:互联网 发布:latex 算法伪代码 编辑:程序博客网 时间:2024/05/18 11:47
题目
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:
Both the array size and each of the array element will not exceed 100.
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.
标签:Dynamic Programming
题意
给定一个非空的只包含正整数的数组,判断是否能将该数组分为两个子集。这两个子集中所有元素的加和相等。
解题思路
如果一个数组可以按照题意分为两个子集,那么每一个子集的和一定等于数组所有数总和的一半。这时这个问题就可以视为一个背包问题,也是背包恰好装满问题:有一个背包,最多能装w重量的物品,有s个物品,每个物品的重量是weights[i]。在s个物品中取任意个使得背包正好装满。
换句话说,在本题中这个问题就变成了,在整个数组中找任意个数,这些数的加和恰好等于数组中数总和的一半。上文中的w是本题中的数组总和的一半,s是数组长度,weights即为nums数组。
代码
public class Solution { public boolean canPartition(int[] nums) { int sum = 0; for (int i : nums) { sum += i; } if (sum % 2 != 0) { return false; } int half = sum / 2; return kp(half, nums.length, nums ); } public boolean kp(int w, int s,int[] nums) { if (w == 0) { return true; } if (w < 0 || w > 0 && s == 0) { return false; } if (kp(w - nums[s - 1], s - 1, nums)) { return true; } return kp(w, s - 1,nums); }}
相关链接
原题
源代码(github)
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
- PEID插件的写法
- css实现文字垂直居中问题
- ffmpeg (七):将h264编码的视频流保存为BMP或者JPEG图片
- union
- Android学习笔记(五*头像)
- leetCode No.416 Partition Equal Subset Sum
- spark 部署在hadoop yarn
- 判断素数
- ELK采集Mysql、Oracle配置
- LSTM
- ImageView圆角处理one
- 动态数组
- 二分法查找
- halcon学习笔记(8)——QT显示halcon处理的图像和结果