|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 698. Partition to K Equal Sum Subsets |
| 5 | + * |
| 6 | + * Given an array of integers nums and a positive integer k, |
| 7 | + * find whether it's possible to divide this array into k non-empty subsets whose sums are all equal. |
| 8 | +
|
| 9 | + Example 1: |
| 10 | +
|
| 11 | + Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 |
| 12 | + Output: True |
| 13 | + Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums. |
| 14 | +
|
| 15 | + Note: |
| 16 | + 1 <= k <= len(nums) <= 16. |
| 17 | + 0 < nums[i] < 10000. |
| 18 | + */ |
| 19 | +public class _698 { |
| 20 | + |
| 21 | + public static class Solution1 { |
| 22 | + public boolean canPartitionKSubsets(int[] nums, int k) { |
| 23 | + long sum = 0; |
| 24 | + for (int num : nums) { |
| 25 | + sum += num; |
| 26 | + } |
| 27 | + if (sum % k != 0) { |
| 28 | + return false; |
| 29 | + } |
| 30 | + int equalSum = (int) (sum / k); |
| 31 | + boolean[] visited = new boolean[nums.length]; |
| 32 | + return canPartition(nums, visited, 0, k, 0, 0, equalSum); |
| 33 | + } |
| 34 | + |
| 35 | + private boolean canPartition(int[] nums, boolean[] visited, int startIndex, int k, int currSum, int currNum, int target) { |
| 36 | + if (k == 1) { |
| 37 | + return true; |
| 38 | + } |
| 39 | + if (currSum == target && currNum > 0) { |
| 40 | + /**Everytime when we get currSum == target, we'll start from index 0 and look up the numbers that are not used yet |
| 41 | + * and try to find another sum that could equal to target*/ |
| 42 | + return canPartition(nums, visited, 0, k - 1, 0, 0, target); |
| 43 | + } |
| 44 | + for (int i = startIndex; i < nums.length; i++) { |
| 45 | + if (!visited[i]) { |
| 46 | + visited[i] = true; |
| 47 | + if (canPartition(nums, visited, i + 1, k, currSum + nums[i], currNum++, target)) { |
| 48 | + return true; |
| 49 | + } |
| 50 | + visited[i] = false; |
| 51 | + } |
| 52 | + } |
| 53 | + return false; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | +} |
0 commit comments