Backtracking Lecture 3
Backtracking Lecture 3
for(int j=indx+1;j<n;j++)
{
char ch= str[j];
rec(j,str,curr+ch,n);
}
}
void powerSet(string str)
{
// code here
sort(str.begin(),str.end());
int n=str.size();
string curr="";
rec(-1,str,curr,n);
}
2. Combination Sum (Adobe, Amazon, Microsoft)
class Solution {
public:
void rec(int i, vector<int>&a, vector<int>&curr,
vector<vector<int>>&ans, int B)
{
if(B==0)
{
ans.push_back(curr);
return;
}
if(B<0 or i==a.size())
{
return;
}
else
{
curr.push_back(a[i]);
rec(i,a,curr,ans,B-a[i]);
curr.pop_back();
rec(i+1,a,curr,ans,B);
}
}
vector<vector<int> > combinationSum(vector<int> &a, int B) {
// Your code here
vector<vector<int>>ans;
vector<int>curr;
int i=0;
sort(a.begin(),a.end());
rec(i,a,curr,ans,B);
return ans;
}
};
class Solution {
public:
int rec(int i, int j, int n, int m, vector<vector<int>>& grid)
{
if(i<0 || j<0 || j==m || i==n || grid[i][j]==0)
{
return 0;
}
grid[i][j]=0;
return max({up,down,right,left});
}
int getMaximumGold(vector<vector<int>>& grid) {
int n = grid.size();
int m= grid[0].size();
int ans=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int amount=0;
if(grid[i][j]!=0)
{
amount= rec(i,j,n,m,grid);
}
if(amount> ans)
{
ans=amount;
}
}
}
return ans;
}
};