Skip to content

Commit 415473f

Browse files
committed
added leetcode programs
1 parent a8550cb commit 415473f

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

cpp/473- Matchsticks_to_Square.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
int a,b,c,d;
3+
bool fun(vector<int>& matchsticks,int i){
4+
if(i==matchsticks.size()){
5+
if(a==0 && b==0 && c==0 && d==0) return true;
6+
else return false;
7+
}
8+
9+
if(matchsticks[i]<=a){
10+
a-=matchsticks[i];
11+
if(fun(matchsticks,i+1)) return true;
12+
a+=matchsticks[i];
13+
}
14+
15+
if(matchsticks[i]<=b){
16+
b-=matchsticks[i];
17+
if(fun(matchsticks,i+1)) return true;
18+
b+=matchsticks[i];
19+
}
20+
21+
if(matchsticks[i]<=c){
22+
c-=matchsticks[i];
23+
if(fun(matchsticks,i+1)) return true;
24+
c+=matchsticks[i];
25+
}
26+
27+
if(matchsticks[i]<=d){
28+
d-=matchsticks[i];
29+
if(fun(matchsticks,i+1)) return true;
30+
d+=matchsticks[i];
31+
}
32+
33+
return false;
34+
}
35+
public:
36+
bool makesquare(vector<int>& matchsticks) {
37+
if(matchsticks.size()<4) return false;
38+
int sum = accumulate(matchsticks.begin(), matchsticks.end(),0);
39+
if(sum % 4 != 0) return false;
40+
int sizeSum=sum/4;
41+
a=sizeSum,b=sizeSum,c=sizeSum,d=sizeSum;
42+
sort(matchsticks.rbegin(), matchsticks.rend());
43+
return fun(matchsticks,0);
44+
}
45+
};

cpp/52- N-Queens_2.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public:
3+
int queen[9];
4+
bool check(int &r,int &c,int n){
5+
for(int i=0;i<r;i++){
6+
// here we have to check from before rows any queen(queen[i]) is placed to attk the cur level queen;
7+
int pre_row=i; // previous row
8+
int pre_col=queen[i]; // previous col is stored in queen[i]
9+
// checking for col collison as rows cant be && and for diagonal attk
10+
if(pre_col==c or abs(r-pre_row)==abs(c-pre_col)) return false;
11+
}
12+
return true;
13+
}
14+
int bt(int level,int n){
15+
// base conditon
16+
17+
if(level==n) return 1;
18+
// return 1 as u made a board and placing queens from 0 to n-1 so u came out of board
19+
20+
int ans=0;
21+
// exploring choices and computation
22+
for(int col=0;col<n;col++){
23+
if(check(level,col,n)){
24+
// check
25+
queen[level]=col;
26+
// move
27+
ans+=bt(level+1,n);
28+
queen[level]=-1;
29+
}
30+
}
31+
// return count of ways to place queen from this row to n-1/ last row
32+
return ans;
33+
}
34+
int totalNQueens(int n) {
35+
memset(queen,-1,sizeof(queen));
36+
return bt(0,n);
37+
}
38+
};

0 commit comments

Comments
 (0)