In this Leetcode Matchsticks to Square problem solution You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Return true if you can make this square and false otherwise.
Problem solution in Python.
class Solution:
def makesquare(self, A: List[int]) -> bool:
n = len(A)
d, m = divmod(sum(A), 4)
if m: return False
A.sort(reverse=True)
if A[-1] > d: return False
used = set()
def rec(i, need):
if i == n: return False
if i in used: return rec(i + 1, need)
if A[i] == need:
used.add(i)
return True
if A[i] < need:
used.add(i)
if rec(i + 1, need - A[i]):
return True
used.remove(i)
return rec(i + 1, need)
for i in range(4):
if not rec(i, d): return False
return True
Problem solution in Java.
public boolean makesquare(int[] nums) {
Long sum=0l;
for(int x:nums){
sum=sum+x;
}
if(sum%4!=0||nums.length<4) return false;
long width=(sum/4);
Arrays.sort(nums);
long sum1=0,sum2=0,sum3=0,sum4=0;
return helper(nums,nums.length-1,sum1,sum2,sum3,sum4,width);
}
public boolean helper(int[] a, int i,long sum1,long sum2,long sum3,long sum4, long width){
if(sum1>width||sum2>width||sum3>width||sum4>width) return false;
if(i==-1){
if(sum1==width&&sum2==width&&sum3==width&&sum4==width) return true;
else return false;
}
//check a[i] belonging to side1,side2,side3,side4
return helper(a,i-1,sum1+a[i],sum2,sum3,sum4,width)||
helper(a,i-1,sum1,sum2+a[i],sum3,sum4,width)||
helper(a,i-1,sum1,sum2,sum3+a[i],sum4,width)||
helper(a,i-1,sum1,sum2,sum3,sum4+a[i],width);
}
Problem solution in C++.
class Solution {
public:
bool found = false;
void help(int pos, vector<int>& matchsticks, int one, int two, int three, int four, long long &sum)
{
if(found)
return;
if(pos == matchsticks.size())
{
if(one == two and two == three and three == four)
found = true;
return;
}
if(one > sum/4 or two > sum/4 or three > sum/4 or four > sum/4)
return;
if(matchsticks.size() - pos >= 4)
help(pos+1, matchsticks, one + matchsticks[pos], two, three, four, sum);
if(matchsticks.size() - pos >= 3)
help(pos+1, matchsticks, one, two + matchsticks[pos], three, four, sum);
if(matchsticks.size() - pos >= 2)
help(pos+1, matchsticks, one, two, three + matchsticks[pos], four, sum);
if(matchsticks.size() - pos >= 1)
help(pos+1, matchsticks, one, two, three, four + matchsticks[pos], sum);
}
bool makesquare(vector<int>& matchsticks)
{
long long sum=0;
for(auto i:matchsticks)
sum += i;
if (matchsticks.size() < 4 or sum % 4)
return false;
// Imp otherwise might get a TLE even after passing all testcases
sort(matchsticks.begin(), matchsticks.end(), greater<int>());
if(matchsticks[0]> (sum/4))
return false;
help(0, matchsticks, 0, 0, 0, 0, sum);
return found;
}
};
0 Comments