LeetCode 题解工作台
分割等和子集
给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。 示例 1: 输入: nums = [1,5,11,5] 输出: true 解释: 数组可以分割成 [1, 5, 5] 和 [11] 。 示例 2: 输入: nums = [1,2…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们先计算出数组的总和 ,如果总和是奇数,那么一定不能分割成两个和相等的子集,直接返回 。如果总和是偶数,我们记目标子集的和为 $m = \frac{s}{2}$,那么问题就转化成了:是否存在一个子集,使得其元素的和为 。 我们定义 表示前 个数中选取若干个数,使得其元素的和恰好为 。初始时 $f[0][0] = true$,其余 $f[i][j] = false$。答案为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
示例 1:
输入:nums = [1,5,11,5] 输出:true 解释:数组可以分割成 [1, 5, 5] 和 [11] 。
示例 2:
输入:nums = [1,2,3,5] 输出:false 解释:数组不能分割成两个元素和相等的子集。
提示:
1 <= nums.length <= 2001 <= nums[i] <= 100
解题思路
方法一:动态规划
我们先计算出数组的总和 ,如果总和是奇数,那么一定不能分割成两个和相等的子集,直接返回 。如果总和是偶数,我们记目标子集的和为 ,那么问题就转化成了:是否存在一个子集,使得其元素的和为 。
我们定义 表示前 个数中选取若干个数,使得其元素的和恰好为 。初始时 ,其余 。答案为 。
考虑 ,如果我们选取了第 个数 ,那么 ;如果我们没有选取第 个数 ,那么 。因此状态转移方程为:
最终答案为 。
时间复杂度 ,空间复杂度 。其中 和 分别为数组的总和的一半和数组的长度。
class Solution:
def canPartition(self, nums: List[int]) -> bool:
m, mod = divmod(sum(nums), 2)
if mod:
return False
n = len(nums)
f = [[False] * (m + 1) for _ in range(n + 1)]
f[0][0] = True
for i, x in enumerate(nums, 1):
for j in range(m + 1):
f[i][j] = f[i - 1][j] or (j >= x and f[i - 1][j - x])
return f[n][m]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understanding of dynamic programming
- question_mark
Ability to optimize space complexity
- question_mark
Awareness of state transitions in dynamic programming solutions
常见陷阱
外企场景- error
Assuming the array can always be partitioned without checking if the sum is even
- error
Incorrectly updating the DP array leading to false positives
- error
Not handling edge cases like very small or large numbers in the array correctly
进阶变体
外企场景- arrow_right_alt
If the array contains negative numbers
- arrow_right_alt
If the array is sorted or unordered
- arrow_right_alt
If there are multiple ways to partition the array