Q:

Write a Java program to divide a given array of integers into given k non-empty subsets whose sums are all equal. Return true if all sums are equal otherwise return false

0

Example:
nums = {1,3,3,5,6,6}, k = 4;
4 subsets (5,1), (3, 3), (6), (6) with equal sums.

Expected Output:

Original Array: [1, 3, 3, 5, 6, 6]
Target of subsets: 4
After removing duplicate characters: true

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Code:

import java.util.*;

public class Solution {
 public static void main(String[] args) {
  int[] nums = {1,3,3,5,6,6};
  int target = 4;
  System.out.print("Original Array: " + Arrays.toString(nums));
  System.out.print("\nTarget of subsets: " + target);
  System.out.print("\nAfter removing duplicate characters: " + partition_k_subsets(nums, target));
 }
 static boolean search_subset(int used, int n, boolean[] flag, int[] nums, int target) {
  if (n == 0) {
   return true;
  }

  if (!flag[used]) {
   flag[used] = true;
   int remain_num = (n - 1) % target + 1;
   for (int i = 0; i & lt; nums.length; i++) {
    if ((((used >> i) & 1) == 0) && nums[i] & lt; = remain_num) {
     if (search_subset(used | (1 & lt; & lt; i), n - nums[i], flag, nums, target)) {
      return true;
     }
    }
   }
  }
  return false;
 }

 public static boolean partition_k_subsets(int[] nums, int k) {
  int sum = Arrays.stream(nums).sum();
  if (sum % k > 0) {
   return false;
  }
  boolean[] flag = new boolean[1 & lt; & lt; nums.length];
  return search_subset(0, sum, flag, nums, sum / k);
 }
}

Output:

Original Array: [1, 3, 3, 5, 6, 6]
Target of subsets: 4
After removing duplicate characters: true

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now