Program to check whether we can partition a list with k-partitions of equal sum in C++


Suppose we have a list of numbers called nums and another value k, we have to check whether it is possible to partition nums into k different subsets where the sum of each subset are same.

So, if the input is like nums = [4, 2, 6, 5, 1, 6, 3] k = 3, then the output will be True, as we can partition them like: [6, 3], [6, 2, 1], and [4, 5].

To solve this, we will follow these steps −

  • Define a function check(), this will take an array v,
  • for initialize i := 1, when i < size of v, update (increase i by 1), do −
    • if v[i] is not equal to v[0], then −
      • return false
  • return true
  • Define a function dfs(), this will take idx, an array nums, an array temp,
  • if idx is same as size of nums, then −
    • return check(temp)
  • ret := false
  • for initialize i := 0, when i < size of temp, update (increase i by 1), do −
    • temp[i] := temp[i] + nums[idx]
    • ret := dfs(idx + 1, nums, temp)
    • if ret is true, then −
      • return true
    • temp[i] := temp[i] - nums[idx]
  • return false
  • From the main method do the following −
  • Define an array temp of size k
  • return dfs(0, nums, temp)

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool check(vector<int>& v) {
      for (int i = 1; i < v.size(); i++) {
         if (v[i] != v[0])
            return false;
      }
      return true;
   }
   bool dfs(int idx, vector<int>& nums, vector<int>& temp) {
      if (idx == nums.size()) {
         return check(temp);
      }
      bool ret = false;
      for (int i = 0; i < temp.size(); i++) {
         temp[i] += nums[idx];
         ret = dfs(idx + 1, nums, temp);
         if (ret)
            return true;
         temp[i] -= nums[idx];
      }
      return false;
   }
   bool solve(vector<int>& nums, int k) {
      vector<int> temp(k);
      return dfs(0, nums, temp);
   }
};
bool solve(vector<int>& nums, int k) {
   return (new Solution())->solve(nums, k);
}
int main(){
   vector<int> v = {4, 2, 6, 5, 1, 6, 3};
   int k = 3;
   cout << solve(v, 3);
}

Input

{4, 2, 6, 5, 1, 6, 3}, 3

Output

1

Updated on: 12-Dec-2020

79 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements