day 29: 22-generate-parentheses, 739-daily-temperatures

This commit is contained in:
Kaushik Narayan R 2023-10-30 12:16:48 -07:00
parent 392b6c97e9
commit 34446fb0a9
6 changed files with 106 additions and 0 deletions

View File

@ -0,0 +1,12 @@
#include "soln.hpp"
int main()
{
int n = 4;
Solution soln;
vector<string> result = soln.generateParenthesis(n);
for (string str : result)
cout << str << "\t";
cout << endl;
return 0;
}

View File

@ -0,0 +1,24 @@
#include "soln.hpp"
void Solution::recurseParenthesis(vector<string> &result, string str, int left, int right)
{
// base case
if (left == 0 & right == 0)
{
result.push_back(str);
return;
}
// opening parenthesis can be added, so add
if (left > 0)
recurseParenthesis(result, str + "(", left - 1, right);
// closing parenthesis can be added, so add
if (right > left)
recurseParenthesis(result, str + ")", left, right - 1);
}
vector<string> Solution::generateParenthesis(int n)
{
vector<string> result;
recurseParenthesis(result, "", n, n);
return result;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
void recurseParenthesis(vector<string>& result, string str, int left, int right);
vector<string> generateParenthesis(int n);
};

View File

@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
vector<int> temps{73, 74, 75, 71, 69, 72, 76, 73};
vector<int> answer{1, 1, 4, 2, 1, 1, 0, 0};
Solution soln;
cout << "Found next warmer days correctly? " << soln.test(temps, answer) << endl;
return 0;
}

View File

@ -0,0 +1,44 @@
#include "soln.hpp"
vector<int> Solution::dailyTemperatures(vector<int> &temperatures)
{
// brute force
// vector<int> answer(temperatures.size());
// for(int i = 0; i < temperatures.size(); i++) {
// bool warmer_day_found = false;
// for(int j = i+1; j < temperatures.size(); j++) {
// if(temperatures[j] > temperatures[i]) {
// warmer_day_found = true;
// answer[i] = j-i;
// break;
// }
// }
// if(!warmer_day_found)
// answer[i] = 0;
// }
// return answer;
// stack, neetcode
vector<int> answer(temperatures.size());
stack<int> dec_temps;
for (int i = 0; i < temperatures.size(); i++)
{
while (!dec_temps.empty() && temperatures[i] > temperatures[dec_temps.top()])
{
answer[dec_temps.top()] = i - dec_temps.top();
dec_temps.pop();
}
dec_temps.push(i);
}
while (!dec_temps.empty())
{
answer[dec_temps.top()] = 0;
dec_temps.pop();
}
return answer;
}
bool Solution::test(vector<int> &temperatures, vector<int> &answer)
{
return dailyTemperatures(temperatures) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> dailyTemperatures(vector<int> &temperatures);
bool test(vector<int> &temperatures, vector<int> &answer);
};