Skip to content

Commit

Permalink
added leetcode programs
Browse files Browse the repository at this point in the history
  • Loading branch information
diva-21 committed Nov 28, 2022
1 parent a8550cb commit 415473f
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
45 changes: 45 additions & 0 deletions cpp/473- Matchsticks_to_Square.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
class Solution {
int a,b,c,d;
bool fun(vector<int>& matchsticks,int i){
if(i==matchsticks.size()){
if(a==0 && b==0 && c==0 && d==0) return true;
else return false;
}

if(matchsticks[i]<=a){
a-=matchsticks[i];
if(fun(matchsticks,i+1)) return true;
a+=matchsticks[i];
}

if(matchsticks[i]<=b){
b-=matchsticks[i];
if(fun(matchsticks,i+1)) return true;
b+=matchsticks[i];
}

if(matchsticks[i]<=c){
c-=matchsticks[i];
if(fun(matchsticks,i+1)) return true;
c+=matchsticks[i];
}

if(matchsticks[i]<=d){
d-=matchsticks[i];
if(fun(matchsticks,i+1)) return true;
d+=matchsticks[i];
}

return false;
}
public:
bool makesquare(vector<int>& matchsticks) {
if(matchsticks.size()<4) return false;
int sum = accumulate(matchsticks.begin(), matchsticks.end(),0);
if(sum % 4 != 0) return false;
int sizeSum=sum/4;
a=sizeSum,b=sizeSum,c=sizeSum,d=sizeSum;
sort(matchsticks.rbegin(), matchsticks.rend());
return fun(matchsticks,0);
}
};
38 changes: 38 additions & 0 deletions cpp/52- N-Queens_2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution {
public:
int queen[9];
bool check(int &r,int &c,int n){
for(int i=0;i<r;i++){
// here we have to check from before rows any queen(queen[i]) is placed to attk the cur level queen;
int pre_row=i; // previous row
int pre_col=queen[i]; // previous col is stored in queen[i]
// checking for col collison as rows cant be && and for diagonal attk
if(pre_col==c or abs(r-pre_row)==abs(c-pre_col)) return false;
}
return true;
}
int bt(int level,int n){
// base conditon

if(level==n) return 1;
// return 1 as u made a board and placing queens from 0 to n-1 so u came out of board

int ans=0;
// exploring choices and computation
for(int col=0;col<n;col++){
if(check(level,col,n)){
// check
queen[level]=col;
// move
ans+=bt(level+1,n);
queen[level]=-1;
}
}
// return count of ways to place queen from this row to n-1/ last row
return ans;
}
int totalNQueens(int n) {
memset(queen,-1,sizeof(queen));
return bt(0,n);
}
};

0 comments on commit 415473f

Please sign in to comment.