Matchsticks to Square in C++


Suppose there is a little match girl. And we know exactly what matchsticks the little match girl has, we have to find out a way we can make one square by using up all those matchsticks. We should not break any stick, but we can link them up, and each matchstick must be used exactly one time. Our input will be several matchsticks the girl has, represented with their stick length. our output will be either true or false, to represent whether we could make one square using all the matchsticks the match girl has. So if the input is like [1,1,2,2,2], then the answer will be true, as we can make a square of length 2, one side will have two sticks of length 1.

To solve this, we will follow these steps −

  • Define a recursive method called solve(). This will take index, sums array, target and nums array. So this will work as follows −
  • if index >= nums size, then
    • return true when sums[0], sum[1] and sum[2] all are same as targer
  • for i in range 0 to 3 −
    • if sums[i] + nums[index] > target, then skip the next part of the loop
    • sums[i] := sums[i] + nums[index]
    • if solve(index + 1, sums, target, nums) is true, then return true
    • sums[i] := sums[i] – nums[index]
  • return false
  • From the main method, do the following −
  • if nums has no elements, then return false
  • x := 0
  • for i in range 0 to size of nums, increase x by nums[j]
  • if x is divisible by 4, then return false
  • sort the nums array
  • make an array sums of size 4
  • return solve(0, sum, x/4, nums)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool solve(int idx, vector <int>& sums, int target, vector <int>& nums){
      if(idx >= nums.size()){
         return sums[0] == sums[1] && sums[1] == sums[2] && sums[2] == target;
      }
      for(int i = 0; i < 4; i++){
         if(sums[i] + nums[idx] > target)continue;
         sums[i] += nums[idx];
         if(solve(idx + 1, sums, target, nums)) return true;
         sums[i] -= nums[idx];
      }
      return false;
   }
   bool makesquare(vector<int>& nums) {
      if(nums.size() == 0) return false;
      int x = 0;
      for(int i = 0; i < nums.size(); i++){
         x += nums[i];
      }
      if(x % 4) return false;
      sort(nums.rbegin(), nums.rend());
      vector <int> sum(4);
      return solve(0, sum,x / 4, nums);
   }
};
main(){
   vector<int> v = {1,1,2,2,2};
   Solution ob;
   cout << (ob.makesquare(v));
}

Input

[1,1,2,2,2]

Output

1

Updated on: 02-May-2020

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements