题目

Given a non-empty array nums 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.

Example 1:

  1. Input: nums = [1,5,11,5]
  2. Output: true
  3. Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

  1. Input: nums = [1,2,3,5]
  2. Output: false
  3. Explanation: The array cannot be partitioned into equal sum subsets.

Constraints:

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100

题意

在一个给定数组中找到一个子数组,使其和为指定值。

思路

使用记忆化搜索容易实现。


代码实现

Java

  1. class Solution {
  2. public boolean canPartition(int[] nums) {
  3. int total = 0;
  4. int left = 0, right = nums.length - 1;
  5. for (int num : nums) {
  6. total += num;
  7. }
  8. if (total % 2 == 1) {
  9. return false;
  10. }
  11. return dfs(total / 2, nums, 0, new Boolean[total / 2 + 1][nums.length]);
  12. }
  13. private boolean dfs(int sum, int[] nums, int start, Boolean[][] record) {
  14. if (start == nums.length) {
  15. return sum == 0;
  16. }
  17. if (sum < 0) {
  18. return false;
  19. }
  20. if (record[sum][start] != null) {
  21. return record[sum][start];
  22. }
  23. boolean found = dfs(sum, nums, start + 1, record) || dfs(sum - nums[start], nums, start + 1, record);
  24. record[sum][start] = found;
  25. return found;
  26. }
  27. }