LeetCode 题解工作台

分割等和子集

给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。 示例 1: 输入: nums = [1,5,11,5] 输出: true 解释: 数组可以分割成 [1, 5, 5] 和 [11] 。 示例 2: 输入: nums = [1,2…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们先计算出数组的总和 ,如果总和是奇数,那么一定不能分割成两个和相等的子集,直接返回 。如果总和是偶数,我们记目标子集的和为 $m = \frac{s}{2}$,那么问题就转化成了:是否存在一个子集,使得其元素的和为 。 我们定义 表示前 个数中选取若干个数,使得其元素的和恰好为 。初始时 $f[0][0] = true$,其余 $f[i][j] = false$。答案为 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 只包含正整数 非空 数组 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
lightbulb

解题思路

方法一:动态规划

我们先计算出数组的总和 ss,如果总和是奇数,那么一定不能分割成两个和相等的子集,直接返回 falsefalse。如果总和是偶数,我们记目标子集的和为 m=s2m = \frac{s}{2},那么问题就转化成了:是否存在一个子集,使得其元素的和为 mm

我们定义 f[i][j]f[i][j] 表示前 ii 个数中选取若干个数,使得其元素的和恰好为 jj。初始时 f[0][0]=truef[0][0] = true,其余 f[i][j]=falsef[i][j] = false。答案为 f[n][m]f[n][m]

考虑 f[i][j]f[i][j],如果我们选取了第 ii 个数 xx,那么 f[i][j]=f[i1][jx]f[i][j] = f[i - 1][j - x];如果我们没有选取第 ii 个数 xx,那么 f[i][j]=f[i1][j]f[i][j] = f[i - 1][j]。因此状态转移方程为:

f[i][j]=f[i1][j] or f[i1][jx] if jxf[i][j] = f[i - 1][j] \textit{ or } f[i - 1][j - x] \textit{ if } j \geq x

最终答案为 f[n][m]f[n][m]

时间复杂度 (m×n)(m \times n),空间复杂度 (m×n)(m \times n)。其中 mmnn 分别为数组的总和的一半和数组的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
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]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Understanding of dynamic programming

  • question_mark

    Ability to optimize space complexity

  • question_mark

    Awareness of state transitions in dynamic programming solutions

warning

常见陷阱

外企场景
  • 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

swap_horiz

进阶变体

外企场景
  • 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

help

常见问题

外企场景

分割等和子集题解:状态·转移·动态规划 | LeetCode #416 中等