1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public boolean canPartition(int[] nums) { int sum = Arrays.stream(nums).sum(); if ((sum & 1) == 1) { return false; }
Set<Integer> memo = new HashSet<>(); int targetSum = sum >> 1; return dfs(nums, 0, 0, targetSum, memo); }
private boolean dfs(int[] nums, int startIndex, int currentSum, int targetSum, Set<Integer> memo) { if (memo.contains(currentSum * 201 + startIndex)) { return false; } if (currentSum == targetSum) { return true; }
if (startIndex < nums.length && currentSum < targetSum) { if (dfs(nums, startIndex + 1, currentSum + nums[startIndex], targetSum, memo)) { return true; } if (dfs(nums, startIndex + 1, currentSum, targetSum, memo)) { return true; } }
memo.add(currentSum * 201 + startIndex); return false; } }
|