416:分割等和子集

This commit is contained in:
huangge1199 2021-08-10 16:43:46 +08:00
parent c21781366e
commit f99d54d01e
2 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1,66 @@
//给你一个 只包含正整数 非空 数组 nums 请你判断是否可以将这个数组分割成两个子集使得两个子集的元素和相等
//
//
//
// 示例 1
//
//
//输入nums = [1,5,11,5]
//输出true
//解释数组可以分割成 [1, 5, 5] [11]
//
// 示例 2
//
//
//输入nums = [1,2,3,5]
//输出false
//解释数组不能分割成两个元素和相等的子集
//
//
//
//
// 提示
//
//
// 1 <= nums.length <= 200
// 1 <= nums[i] <= 100
//
// Related Topics 数组 动态规划
// 👍 888 👎 0
package leetcode.editor.cn;
//416:分割等和子集
class PartitionEqualSubsetSum {
public static void main(String[] args) {
//测试代码
Solution solution = new PartitionEqualSubsetSum().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
int length = nums.length;
if (sum % 2 == 1)
return false;
boolean[][] dp = new boolean[length + 1][sum / 2 + 1];
dp[0][0] = true;
for (int i = 1; i <= length; i++) {
for (int j = 0; j <= sum / 2; j++) {
if (j >= nums[i - 1]) {
dp[i][j] |= dp[i - 1][j - nums[i - 1]];
}
dp[i][j] |= dp[i - 1][j];
}
}
return dp[length][sum / 2];
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,28 @@
<p>给你一个 <strong>只包含正整数 </strong><strong>非空 </strong>数组 <code>nums</code> 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>nums = [1,5,11,5]
<strong>输出:</strong>true
<strong>解释:</strong>数组可以分割成 [1, 5, 5] 和 [11] 。</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>nums = [1,2,3,5]
<strong>输出:</strong>false
<strong>解释:</strong>数组不能分割成两个元素和相等的子集。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 200</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
<div><div>Related Topics</div><div><li>数组</li><li>动态规划</li></div></div>\n<div><li>👍 888</li><li>👎 0</li></div>