0698. Partition to K Equal Sum Subsets

https://leetcode.com/problems/partition-to-k-equal-sum-subsets

Description

Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.

Example 1:

**Input:** nums = [4,3,2,3,5,2,1], k = 4
**Output:** true
**Explanation:** It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.

Example 2:

**Input:** nums = [1,2,3,4], k = 3
**Output:** false

Constraints:

  • 1 <= k <= nums.length <= 16

  • 1 <= nums[i] <= 104

  • The frequency of each element is in the range [1, 4].

ac1: DFS

class Solution {
    public boolean canPartitionKSubsets(int[] nums, int k) {
        // edge cases
        if (nums == null || nums.length == 0 || k <= 0 || nums.length < k) return false;

        int sum = 0;
        for (int n : nums) sum += n;
        if (sum % k != 0) return false;

        return helper(nums, 0, new boolean[nums.length], 0, sum/k, k-1);
    }

    private boolean helper(int[] nums, int startIndex, boolean[] visited, int currSum, int targetSum, int remainSubset) {
        // exit
        if (currSum > targetSum) {  // this element not good, find next
            return false;
        } else if (currSum == targetSum) {  // find one subset
            if (remainSubset == 0) return true; // last subset, since every subset meet target sum, and it has k subset, so return true
            else return helper(nums, 0, visited, 0, targetSum, remainSubset-1);  // go into next subset
        }

        // find elements add up to targetSum
        for (int i = startIndex; i < nums.length; i++) {  // startIndex avoid duplicate, O(2^n)
            if (visited[i]) continue;
            visited[i] = true;
            if (helper(nums, i+1, visited, currSum+nums[i], targetSum, remainSubset)) return true;
            visited[i] = false;
        }

        return false;
    }
}

Last updated