init: init commit
All checks were successful
Build and Deploy Quartz / build-and-deploy (push) Has been skipped
All checks were successful
Build and Deploy Quartz / build-and-deploy (push) Has been skipped
This commit is contained in:
19
content/Leetcode Questions/Leetcode Questions Base.base
Normal file
19
content/Leetcode Questions/Leetcode Questions Base.base
Normal file
@@ -0,0 +1,19 @@
|
||||
filters:
|
||||
and:
|
||||
- file.inFolder("Leetcode Questions")
|
||||
- file.ext == "md"
|
||||
views:
|
||||
- type: table
|
||||
name: Table
|
||||
order:
|
||||
- file.name
|
||||
- title
|
||||
- date
|
||||
- file.tags
|
||||
- file.mtime
|
||||
sort:
|
||||
- property: date
|
||||
direction: DESC
|
||||
columnSize:
|
||||
note.title: 162
|
||||
file.tags: 256
|
||||
@@ -0,0 +1,126 @@
|
||||
---
|
||||
tags:
|
||||
- Greedy
|
||||
- Heap
|
||||
date: 2025-12-22
|
||||
---
|
||||
|
||||
[Leetcode Question Link](https://leetcode.com/problems/maximize-happiness-of-selected-children/?envType=daily-question&envId=2025-12-25)
|
||||
|
||||
For the convenience, we use $a[i]$ to denote $\text{happiness}[i]$ in article below.
|
||||
|
||||
# Analysis
|
||||
|
||||
## Gain From One Child
|
||||
|
||||
Consider if we chose children $i$ at time $t, \;t \in [0, k)$, what could we add to the final sum?
|
||||
|
||||
If not considering our choice, the lost of the happiness $L$ should be:
|
||||
|
||||
$$
|
||||
L(i) = min(a[i], k)
|
||||
$$
|
||||
|
||||
- If $a[i] \le k$, this means the $a[i]$ will goes to $0$ before the procedure finished, so the maximum decrease of the value is from $a[i]$ to $0$, that is, $L = a[i]$
|
||||
- If $a[i] > k$, that means $a[i]$ never reach $0$, the decrease value is exactly the round $k$. So we have $L = k$.
|
||||
|
||||
Now take our choice operation into consideration. If we chose a child at time $t$, then the actual lost of happiness of this child should be:
|
||||
|
||||
$$
|
||||
L_{A}(i, t) = min(L(i), t)
|
||||
$$
|
||||
|
||||
- If $t < L$, means we chose this child while it's decreasing, this means if we chose this child, it should be decreasing from time $0$ to time $t$, the actual decrease value $L_{A} = t$.
|
||||
- If $t > L$, means this child's happiness already stop decreasing, our action of choice actually has no effect, so $L_{A} = L$.
|
||||
|
||||
-----
|
||||
|
||||
In conclusion, we could know that for any child $i$, if we choice it, the happiness value $H$ we could get will be:
|
||||
|
||||
$$
|
||||
\begin{align}
|
||||
H(i, t) &= a[i] - L_{A}(i, t) \\[1em]
|
||||
&= a[i] - min(min(a[i], k), t) \\[1em]
|
||||
&= a[i] - min(a[i], k, t)
|
||||
\end{align}
|
||||
$$
|
||||
|
||||
## Choose Child
|
||||
|
||||
Based on analysis above, we should be aware that the greedy strategy could be used for this question. That is, **to ensure highest final sum, we should always choose child with largest initial happiness first**.
|
||||
|
||||
Consider the formula of $H(i, t)$:
|
||||
|
||||
$$
|
||||
H(i, t) = a[i] - min(a[i], k, t)
|
||||
$$
|
||||
|
||||
If we want to make $H(i, t)$ larger, we need to make $min(a[i], k, t)$ smaller, so we should put larger $a[i]$ with smaller $t$. And that, in this problem, means choose child with larger happiness sooner.
|
||||
|
||||
# Code
|
||||
|
||||
```cpp
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <queue>
|
||||
#include <vector>
|
||||
|
||||
using std::priority_queue;
|
||||
using std::vector;
|
||||
|
||||
bool debug = false;
|
||||
|
||||
struct MyMinHeap : std::priority_queue<int, std::vector<int>, std::greater<int>> {
|
||||
void reserve(size_t n) { this->c.reserve(n); }
|
||||
};
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
long long maximumHappinessSum(vector<int>& happiness, int k) {
|
||||
// min heap
|
||||
MyMinHeap maxk;
|
||||
maxk.reserve(k);
|
||||
int cur, top;
|
||||
|
||||
// initial heap with k elements
|
||||
for (int i = 0; i < k; ++i) {
|
||||
maxk.push(happiness[i]);
|
||||
}
|
||||
// iterate while update
|
||||
for (int i = k; i < happiness.size(); ++i) {
|
||||
cur = happiness[i];
|
||||
top = maxk.top();
|
||||
|
||||
// current elements smaller, just continue
|
||||
if (cur <= top) {
|
||||
continue;
|
||||
}
|
||||
// update elements
|
||||
maxk.pop();
|
||||
maxk.push(cur);
|
||||
}
|
||||
|
||||
// at this point, all max-k elements are in the min heap
|
||||
|
||||
long long answer = 0;
|
||||
int chooseTime, lost;
|
||||
for (chooseTime = k - 1; chooseTime >= 0; --chooseTime) {
|
||||
// get top element
|
||||
cur = maxk.top();
|
||||
maxk.pop();
|
||||
|
||||
if (debug) {
|
||||
cout << "choosed: " << cur << endl;
|
||||
}
|
||||
|
||||
// determine the lost of this element
|
||||
lost = std::min({k, cur, chooseTime});
|
||||
|
||||
// update answer
|
||||
answer += (cur - lost);
|
||||
}
|
||||
|
||||
return answer;
|
||||
}
|
||||
};
|
||||
```
|
||||
347
content/Leetcode Questions/Meeting Rooms III.md
Normal file
347
content/Leetcode Questions/Meeting Rooms III.md
Normal file
@@ -0,0 +1,347 @@
|
||||
---
|
||||
date: 2025-12-29
|
||||
tags:
|
||||
- Simulation
|
||||
- "#Heap"
|
||||
---
|
||||
|
||||
[Leetcode question link](https://leetcode.com/problems/meeting-rooms-iii)
|
||||
|
||||
# Analysis
|
||||
|
||||
Basically this is just an #Simulation problem.
|
||||
|
||||
> [!note]
|
||||
>
|
||||
> The most important time complexity optimization is to find out the **unused room management could exploit #Heap data structure**, checkout [[#Room Distribution Order]] for details
|
||||
|
||||
## Meeting Distribution Order
|
||||
|
||||
Since the `startTime` is promised to be unique, based on the rule, we know that the **distribution should goes from meetings with smaller `startTime` to larger one**. The basic thought is:
|
||||
|
||||
1. Sort `meetings`
|
||||
2. Distribute `meeting` to room, counting usage statistics of each room
|
||||
3. Output most used room
|
||||
|
||||
## Room Distribution Order
|
||||
|
||||
Based on the rules, we know that the room being distributed is **always the one with the smallest room number and currently available**. Conclude what operations we need for rooms.
|
||||
|
||||
| Operation | Descriptions |
|
||||
| ---------------- | ----------------------------------------------------------------------------------------------- |
|
||||
| `use()` | Mark a room used, that room should have the lowest `roomIdx` among all currently available room |
|
||||
| `unuse(roomIdx)` | Unuse a room by it's index |
|
||||
|
||||
Here we introduce two approaches to achieve these.
|
||||
|
||||
### Array
|
||||
|
||||
We use an array `bool isUsed[N]` to record the status of a room. This require us to iterate the array to find out the lowest unused index, thus has time complexity $O(N)$
|
||||
|
||||
### Min Heap
|
||||
|
||||
We could find Minimum Heap suit this use case really well. We initial a min heap with all unused room index, and:
|
||||
|
||||
- `use()` Remove the index at the heap top
|
||||
- `unuse()` Insert the index to the heap
|
||||
|
||||
By doing this, we could have $O(\log N)$ time complexity, considering $N$ is the number of room.
|
||||
|
||||
# Code Implementation
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
#include <format>
|
||||
#include <algorithm>
|
||||
#include <queue>
|
||||
|
||||
using std::cout, std::endl, std::format;
|
||||
|
||||
using std::vector, std::priority_queue;
|
||||
|
||||
const bool debug = false;
|
||||
|
||||
struct TaskInfo
|
||||
{
|
||||
unsigned start = 0;
|
||||
unsigned end = 0;
|
||||
|
||||
TaskInfo(const vector<int> &vec) : start(vec[0]), end(vec[1]) {}
|
||||
|
||||
bool operator<(const TaskInfo &other)
|
||||
{
|
||||
if (start != other.start)
|
||||
{
|
||||
return start < other.start;
|
||||
}
|
||||
|
||||
return end < other.end;
|
||||
}
|
||||
|
||||
unsigned duration() const
|
||||
{
|
||||
return end - start;
|
||||
}
|
||||
|
||||
void delay(unsigned delta)
|
||||
{
|
||||
start += delta;
|
||||
end += delta;
|
||||
}
|
||||
|
||||
void relocate(unsigned startTime)
|
||||
{
|
||||
end = startTime + duration();
|
||||
start = startTime;
|
||||
}
|
||||
};
|
||||
|
||||
class MeetingRoomManager
|
||||
{
|
||||
private: // private member
|
||||
vector<unsigned> mUseCount;
|
||||
unsigned tmpMostUsedCount = 0;
|
||||
std::priority_queue<unsigned, std::vector<unsigned>, std::greater<unsigned>> tmpUnusedIdxHeap;
|
||||
|
||||
public: // public member
|
||||
// the count of the room
|
||||
unsigned mCount = 0;
|
||||
|
||||
public: // public method
|
||||
// initialize manager with room count
|
||||
MeetingRoomManager(int count) : mCount(count)
|
||||
{
|
||||
mUseCount = vector<unsigned>(100);
|
||||
|
||||
clear(count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a valid room, mark it as used and update the use count.
|
||||
* Return index of the used room.
|
||||
*
|
||||
* Return 100 if room not found.
|
||||
*/
|
||||
unsigned use()
|
||||
{
|
||||
// room not found
|
||||
if (tmpUnusedIdxHeap.empty())
|
||||
{
|
||||
return 100;
|
||||
}
|
||||
|
||||
// found room with lowest index
|
||||
unsigned unuse = tmpUnusedIdxHeap.top();
|
||||
tmpUnusedIdxHeap.pop();
|
||||
|
||||
++mUseCount[unuse]; // update use count
|
||||
|
||||
// update most use if needed
|
||||
if (mUseCount[unuse] > tmpMostUsedCount)
|
||||
{
|
||||
tmpMostUsedCount = mUseCount[unuse];
|
||||
}
|
||||
|
||||
return unuse; // return room idx
|
||||
}
|
||||
|
||||
/**
|
||||
* Unuse a room by its index
|
||||
*/
|
||||
void unuse(unsigned roomIdx)
|
||||
{
|
||||
tmpUnusedIdxHeap.push(roomIdx);
|
||||
}
|
||||
|
||||
unsigned mostUsedIdx()
|
||||
{
|
||||
for (int i = 0; i < mCount; ++i)
|
||||
{
|
||||
if (mUseCount[i] == tmpMostUsedCount)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool isFull()
|
||||
{
|
||||
return tmpUnusedIdxHeap.empty();
|
||||
}
|
||||
|
||||
void clear(unsigned count)
|
||||
{
|
||||
// reset mCount
|
||||
mCount = count;
|
||||
// clear most use count
|
||||
tmpMostUsedCount = 0;
|
||||
// clear use count statistics
|
||||
std::fill(mUseCount.begin(), mUseCount.end(), false);
|
||||
// init unuse heap
|
||||
tmpUnusedIdxHeap = std::priority_queue<unsigned, std::vector<unsigned>, std::greater<unsigned>>();
|
||||
for (int i = 0; i < mCount; ++i)
|
||||
{
|
||||
tmpUnusedIdxHeap.push(i);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class RoomDistributor
|
||||
{
|
||||
|
||||
private: // private classes
|
||||
struct FutureReleaseInfo
|
||||
{
|
||||
unsigned time;
|
||||
unsigned roomIdx;
|
||||
|
||||
bool operator<(const FutureReleaseInfo &other) const
|
||||
{
|
||||
if (time != other.time)
|
||||
{
|
||||
return time > other.time;
|
||||
}
|
||||
return roomIdx > other.roomIdx;
|
||||
}
|
||||
};
|
||||
|
||||
private: // private members
|
||||
// manage room usage info
|
||||
MeetingRoomManager mManager;
|
||||
// record current timestamp
|
||||
unsigned mCurTimestamp = 0;
|
||||
// record when to release room
|
||||
std::priority_queue<FutureReleaseInfo> mReleaseTimeHeap;
|
||||
|
||||
private: // private methods
|
||||
// release one from heap
|
||||
// will NOT check empty before action!
|
||||
void releaseOne()
|
||||
{
|
||||
const FutureReleaseInfo &nextReleaseInfo = mReleaseTimeHeap.top();
|
||||
|
||||
mManager.unuse(nextReleaseInfo.roomIdx);
|
||||
mCurTimestamp = std::max({nextReleaseInfo.time, mCurTimestamp});
|
||||
mReleaseTimeHeap.pop();
|
||||
}
|
||||
|
||||
// release all the room until the given timestamp
|
||||
void pushTimeTo(unsigned targetTime)
|
||||
{
|
||||
|
||||
// already pushed to a time later then given, nothing to do
|
||||
if (mCurTimestamp > targetTime)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// no room is used, just move the time
|
||||
if (mReleaseTimeHeap.empty())
|
||||
{
|
||||
mCurTimestamp = targetTime;
|
||||
return;
|
||||
}
|
||||
|
||||
// release until target time
|
||||
while (!mReleaseTimeHeap.empty() && mReleaseTimeHeap.top().time <= targetTime)
|
||||
{
|
||||
releaseOne();
|
||||
}
|
||||
mCurTimestamp = targetTime;
|
||||
}
|
||||
|
||||
public:
|
||||
RoomDistributor(unsigned roomCount) : mManager(roomCount) {}
|
||||
|
||||
// distribute a meeting task to the room
|
||||
void distributeTask(const TaskInfo &taskInfo)
|
||||
{
|
||||
pushTimeTo(taskInfo.start);
|
||||
|
||||
// if room still full, push timestamp until next room release
|
||||
if (mManager.isFull())
|
||||
{
|
||||
releaseOne();
|
||||
}
|
||||
|
||||
// distribute a room
|
||||
unsigned roomIdx = mManager.use();
|
||||
// record a new future release
|
||||
mReleaseTimeHeap.emplace(FutureReleaseInfo(mCurTimestamp + taskInfo.duration(), roomIdx));
|
||||
}
|
||||
|
||||
/**
|
||||
* Release all item that should be released in the future
|
||||
*/
|
||||
void releaseAll()
|
||||
{
|
||||
while (!mReleaseTimeHeap.empty())
|
||||
{
|
||||
releaseOne();
|
||||
}
|
||||
}
|
||||
|
||||
unsigned getMostUsedIdx()
|
||||
{
|
||||
return mManager.mostUsedIdx();
|
||||
}
|
||||
|
||||
void clear(unsigned count)
|
||||
{
|
||||
// reset timestamp
|
||||
mCurTimestamp = 0;
|
||||
// clean heap
|
||||
releaseAll();
|
||||
// clear mManager
|
||||
mManager.clear(count);
|
||||
}
|
||||
};
|
||||
|
||||
// global variables
|
||||
unsigned roomCount, meetingCount;
|
||||
RoomDistributor distributor(0);
|
||||
vector<TaskInfo> tasks;
|
||||
|
||||
void initVariables(const vector<vector<int>> &meetings)
|
||||
{
|
||||
// init tasks
|
||||
tasks.clear();
|
||||
tasks.reserve(meetings.size());
|
||||
for (const auto &m : meetings)
|
||||
{
|
||||
tasks.emplace_back(TaskInfo(m));
|
||||
}
|
||||
std::sort(tasks.begin(), tasks.end());
|
||||
|
||||
// init distributor
|
||||
distributor.clear(roomCount);
|
||||
}
|
||||
|
||||
void triggerSimulation()
|
||||
{
|
||||
for (const auto &t : tasks)
|
||||
{
|
||||
distributor.distributeTask(t);
|
||||
}
|
||||
|
||||
distributor.releaseAll();
|
||||
}
|
||||
|
||||
class Solution
|
||||
{
|
||||
public:
|
||||
int mostBooked(int n, vector<vector<int>> &meetings)
|
||||
{
|
||||
roomCount = n;
|
||||
meetingCount = meetings.size();
|
||||
|
||||
initVariables(meetings);
|
||||
triggerSimulation();
|
||||
|
||||
return distributor.getMostUsedIdx();
|
||||
}
|
||||
};
|
||||
```
|
||||
75
content/Leetcode Questions/Minimum Penalty For a Shop.md
Normal file
75
content/Leetcode Questions/Minimum Penalty For a Shop.md
Normal file
@@ -0,0 +1,75 @@
|
||||
---
|
||||
tags:
|
||||
- Greedy
|
||||
- Array
|
||||
date: 2025-12-26
|
||||
---
|
||||
|
||||
[Leetcode Question Link](https://leetcode.com/problems/minimum-penalty-for-a-shop)
|
||||
|
||||
# Analysis
|
||||
|
||||
## Offset
|
||||
|
||||
The target is to **find the time to achieve the smallest penalty, but not the penalty value itself**. So the concrete value of penalty is not important, we could just focus on **how penalty changes when changing shop closing time**.
|
||||
|
||||
Let `offset` be the penalty diff when choosing closing time $i$ and closing time $0$, that is:
|
||||
|
||||
$$
|
||||
\text{offset}(i) = \text{penalty}(i) - \text{penalty}(0)
|
||||
$$
|
||||
|
||||
## Moving Closing Time
|
||||
|
||||
Now let's find how $\text{offset}(i)$ changes when $i: 0 \to n$.
|
||||
|
||||
---
|
||||
|
||||
When $i = 0$, based on definition of offset, we have $\text{offset}(0) = 0$
|
||||
|
||||
-----
|
||||
|
||||
When we moving closing time $i$ from $k - 1$ to $k$, discuss:
|
||||
|
||||
**When at $k-1$ hour, there IS customers arriving.** In this case, before moving closing time, there is an $Y$ in closing time, after moving, the $Y$ has been moved into open time. So $\text{offset}$ actually decrease by $1$ after moving.
|
||||
|
||||
**When at $k-1$ hour, there IS NOT customers arriving.** by similar analysis method, we know there is an $N$ moved from closing time to opening time, $\text{offset}$ increase by $1$.
|
||||
|
||||
# Code Implementation
|
||||
|
||||
```cpp
|
||||
class Solution {
|
||||
public:
|
||||
int bestClosingTime(string customers) {
|
||||
|
||||
// init offset
|
||||
// at time 0, offset = 0
|
||||
int offset = 0, minOffset = 0;
|
||||
unsigned minTime = 0;
|
||||
bool arrived;
|
||||
|
||||
int rangeEnd = customers.size() + 1;
|
||||
for (int i = 1; i < rangeEnd; ++i) {
|
||||
|
||||
// check if there is customers arrived at previous time
|
||||
arrived = (customers[i - 1] == 'Y' ? 1 : 0);
|
||||
|
||||
// someone arrived, then moving closing time
|
||||
// 1 hour later will cause offset decreasing by 1,
|
||||
// otherwise, offset increasing by 1
|
||||
if (arrived)
|
||||
--offset;
|
||||
else
|
||||
++offset;
|
||||
|
||||
// update minOffset and minTime
|
||||
if (offset < minOffset) {
|
||||
minOffset = offset;
|
||||
minTime = i;
|
||||
}
|
||||
}
|
||||
|
||||
return minTime;
|
||||
}
|
||||
};
|
||||
```
|
||||
602
content/Leetcode Questions/Pyramid Transition Matrix.md
Normal file
602
content/Leetcode Questions/Pyramid Transition Matrix.md
Normal file
@@ -0,0 +1,602 @@
|
||||
---
|
||||
date: 2025-12-31
|
||||
tags:
|
||||
- DFS
|
||||
- Search
|
||||
- Cache
|
||||
---
|
||||
[Leetcode Question Link](https://leetcode.com/problems/pyramid-transition-matrix/)
|
||||
|
||||
# Analyze
|
||||
|
||||
## Basic Thought
|
||||
|
||||
For each pyramid block, the possible color (represented by one single character) is limited to following:
|
||||
|
||||
```
|
||||
color = A, B, C, D, E, F
|
||||
```
|
||||
|
||||
The intuitive is to use #Search to **iterate through the solution space** *(all possible value of the elements in pyramid)* to find the final answer.
|
||||
|
||||
## Searching
|
||||
|
||||
### Store Current Search State
|
||||
|
||||
The the image shows below, we store the pyramid info info an 2D `char` array:
|
||||
|
||||
![[251231_store_search_info.png]]
|
||||
|
||||
And define meaning of the value in the elements as follow:
|
||||
|
||||
| Value | Description |
|
||||
| ------- | ---------------- |
|
||||
| `0` | Not yet searched |
|
||||
| `[A-F]` | Searching |
|
||||
| `1` | Searched |
|
||||
|
||||
### Search Direction
|
||||
|
||||
We search **from right to left, from bottom to top**. More concretely, consider current searching position is `[curR][curC]`, then next search position could be calculated by code below:
|
||||
|
||||
```python
|
||||
def pos_forward(curR, curC):
|
||||
if(curC > 0):
|
||||
--curC # one step left
|
||||
else:
|
||||
--curR # search the layer above
|
||||
curC = curR # start from right-most element
|
||||
```
|
||||
|
||||
> [!note]
|
||||
>
|
||||
> Please note that all Python code in this post is intended solely to illustrate the logic and should be regarded as pseudocode.
|
||||
>
|
||||
> For runnable C++ code, checkout [[#Code Implementation]] sector.
|
||||
|
||||
![[251231_search_direction.png]]
|
||||
|
||||
### Search Implementation
|
||||
|
||||
I decided to use a **non-recursive way** to implement DFS search in the solution space.
|
||||
|
||||
The search strategy could be explained by the code below:
|
||||
|
||||
```python
|
||||
def _search():
|
||||
# global variables
|
||||
global curR
|
||||
global curC
|
||||
|
||||
# if already found valid answer, or search already finished
|
||||
# return directly
|
||||
if found or finished:
|
||||
return
|
||||
|
||||
# search for this position is finished
|
||||
if currChar == '1':
|
||||
|
||||
# if this is the search starting point
|
||||
# then it means the whole solution space has been searched
|
||||
if [curR, curC] == [bottom_size - 1, bottom_size - 1]:
|
||||
finished = True
|
||||
return
|
||||
|
||||
# else, we go one step backward.
|
||||
#
|
||||
# setting current position value to '0' is necessary,
|
||||
# since if not doing so, next time we search this position,
|
||||
# program will directly skip searching and go backward()
|
||||
currChar == '0'
|
||||
pos_backward()
|
||||
return
|
||||
|
||||
# at here, the search of current position must NOT finished
|
||||
currChar = next_possible_char_for_this_pos()
|
||||
|
||||
# this is the last position to search, and we found a valid color
|
||||
if currChar != '1' and [curR, curC] == [0, 0]:
|
||||
found = True
|
||||
return
|
||||
|
||||
pos_forward()
|
||||
|
||||
|
||||
def search() -> bool:
|
||||
while (not finished) and (not found):
|
||||
_search()
|
||||
|
||||
return found
|
||||
```
|
||||
|
||||
In code above:
|
||||
|
||||
- `pos_forward() / pos_backward()` modify `curR, curC` to point to next / previous search position
|
||||
- `next_possible_char_for_this_pos()` will return next valid color character for current position based on allowed patterns and values in `[curR + 1][curC]` and `[curR + 1][curC + 1]`
|
||||
|
||||
```python
|
||||
def next_possible_char_for_this_pos():
|
||||
if curChar == '0':
|
||||
curChar = 'A' - 1
|
||||
|
||||
curChar++
|
||||
|
||||
while curChar <= 'F'
|
||||
is_valid = check_pattern(
|
||||
top=curChar,
|
||||
bottom_left=pyramid[curR + 1][curC],
|
||||
bottom_right=pyramid[curR + 1][curC + 1],
|
||||
)
|
||||
if is_valid:
|
||||
break
|
||||
|
||||
if curChar > 'F':
|
||||
curChar = '1'
|
||||
```
|
||||
|
||||
## Caching
|
||||
|
||||
Purely solution space searching **without any cache** could **not pass all the testcase** *(due to `TLE`)*.
|
||||
|
||||
Therefore, we need to exploit the info produced during searching to **cache some impossible answer of sub-question** and use such cache in proper time.
|
||||
|
||||
### Set Cache
|
||||
|
||||
We could trigger set cache when **searching position change to the lower layer**.
|
||||
|
||||
Let's say, the position row index *(or we could say, layer index)* from `curR = 1` to `curR = 2`, then at this point, we could be sure the sub question using bottom sequence as current layer 2 is impossible.
|
||||
|
||||
![[251231_no_solution.png]]
|
||||
|
||||
This is because, if such sub question `B, D, C` have solution, the search position will finally go to the `curR = 0, curC = 0` and set `found = 1`, thus, the search is finished, and we found a valid solution for original question, and such solution use `B, D, C` as layer 2 elements.
|
||||
|
||||
> [!note]
|
||||
>
|
||||
> Here, sub question of a sequence means that: "If we could find a possible pyramid if the bottom is such sequence".
|
||||
>
|
||||
> For example, sub question using `B, D, C` as sequence means if we could find a valid pyramid that using `B, D, C` as the pyramid bottom.
|
||||
|
||||
### Use Cache
|
||||
|
||||
Based on analysis above, it's easy to know we could use cache when **searching position changes to higher layer**.
|
||||
|
||||
![[251231_use_cache.png]]
|
||||
|
||||
As the image above, when we goes from `[2][0]` to `[1][1]`, before start searching, we first check if the sub questions of layer 2: `B, D, C` is in the cache.
|
||||
|
||||
If cache hit, it means such **sub question has no solution** and we should **not wasting time searching further** anymore. Instead, we directly go back to `[2][0]` again, set it to next possible value *(for example from `B` to `C` in the image)* then keep searching.
|
||||
|
||||
> [!note]
|
||||
>
|
||||
> We **only need to cache the invalid sub questions**, thus, the cache could be stored in a set, e.g. `std::unordered_set<std::string> cache`. As long as a string sequence is in the cache *(could be checked using `cache.contains(str)`)*, we can sure it doesn't have solution.
|
||||
|
||||
> [!note]
|
||||
>
|
||||
> It's easy to proof **we don't need to cache the "valid" solution** of any sub question. Reusing example above, if the `B, D, C` sub sequence is valid as a pyramid bottom, then we will not even have a chance to cache it since the search procedure will reach the top of pyramid and declare `found = true`.
|
||||
>
|
||||
> In other word, if any sub question is valid in our definition, it must also indicate the original question solution is also being found.
|
||||
|
||||
## More About Cache
|
||||
|
||||
At the beginning, I'm actually thinking about another way of recording cache. That is, when we **find a valid value for position `[i][j]`,** then if we **use this position as pyramid top to consider the sub-pyramid**, then **all the layer should be able to considered a valid sequence** as a sub question.
|
||||
|
||||
![[251231_another_way_of_cache.png]]
|
||||
|
||||
Use the image above as an example, if during the searching procedure, we **found that `D` as a valid color for position `[2][1]`,** then we should be able to ensure the **layers of the sub-pyramid are all valid sequences as sub-question**, that is:
|
||||
|
||||
```
|
||||
seq1 = C, D
|
||||
seq2 = E, F, A
|
||||
seq3 = ...
|
||||
```
|
||||
|
||||
**All these sequences should be consider valid**, since when any of them is considered as the bottom, we **could found at least a valid pyramid that satisfies the constrain of the question** simply based on the sub-pyramid *(the green and blue part in the image)* we found.
|
||||
|
||||
> [!note]
|
||||
>
|
||||
> In this case, if we **can not find any valid value for position `[1][2]`,** we **can NOT say** conversely that **any layer for the sub-pyramid is not valid**.
|
||||
>
|
||||
> This is easy to understand, actually we could ensure `C, D` is not a valid pyramid bottom, however, that doesn't mean `E, F, A` is not valid, since it may have other available sequence other than `C, D` as the upper layer of `E, F, A`
|
||||
|
||||
-----
|
||||
|
||||
I tried writing solution code using this thought, triggering cache but it turns out I got `TLE`. The basic code logic I implement is like below:
|
||||
|
||||
```python
|
||||
# if we should trigger cache for current position for now?
|
||||
def should_trigger_cache(curR, curC) -> bool:
|
||||
# only trigger cache when a position is being searched
|
||||
# at the first time in current sub solution space
|
||||
if currChar != '0':
|
||||
return False
|
||||
|
||||
# first search, but no valid value for current position
|
||||
# then do not cache
|
||||
if next_possible_char_for_this_pos() == '1':
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
# perform caching for all sequences of sub pyramid
|
||||
def set_cache_for_sub_pyramid(curR, curC):
|
||||
for string in get_sub_pyramid_layers_as_string():
|
||||
cache.add(seq=string, value=True)
|
||||
```
|
||||
|
||||
Personally I guess the cost of caching sub-pyramid for every position every time it's first searched in a sub solution space is too high, but I can't figure out a better approach lol
|
||||
|
||||
# Code Implementation
|
||||
|
||||
```cpp
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <numeric>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
using std::cout, std::endl;
|
||||
using std::format;
|
||||
using std::vector, std::string;
|
||||
|
||||
bool debug = false;
|
||||
|
||||
/**
|
||||
* Data structure to store pattern in question
|
||||
*
|
||||
* Init:
|
||||
* - Use 3-char string to init (based on questoni definition)
|
||||
* - Use three different char parameter to init
|
||||
*
|
||||
* Method:
|
||||
* - Equal comparator
|
||||
* - hash() function
|
||||
*/
|
||||
struct Pattern
|
||||
{
|
||||
char top;
|
||||
char left;
|
||||
char right;
|
||||
|
||||
Pattern(const string &data)
|
||||
{
|
||||
top = data[2];
|
||||
left = data[0];
|
||||
right = data[1];
|
||||
}
|
||||
|
||||
Pattern(char top, char left, char right)
|
||||
: top(top), left(left), right(right) {}
|
||||
|
||||
bool operator==(const Pattern &other) const
|
||||
{
|
||||
return top == other.top && left == other.left && right == other.right;
|
||||
}
|
||||
|
||||
size_t hash() const
|
||||
{
|
||||
return std::hash<char>()(top) + std::hash<char>()(left) +
|
||||
std::hash<char>()(right);
|
||||
}
|
||||
};
|
||||
|
||||
struct PatternHash
|
||||
{
|
||||
size_t operator()(const Pattern &p) const { return p.hash(); }
|
||||
};
|
||||
|
||||
class PatternManager
|
||||
{
|
||||
private:
|
||||
std::unordered_set<Pattern, PatternHash> mPatterns;
|
||||
bool mPairs[6][6];
|
||||
|
||||
public:
|
||||
PatternManager()
|
||||
{
|
||||
clear();
|
||||
}
|
||||
|
||||
void add(const Pattern &p)
|
||||
{
|
||||
mPatterns.insert(p);
|
||||
mPairs[p.left - 'A'][p.right - 'A'] = 1;
|
||||
}
|
||||
|
||||
bool exists(const Pattern &p)
|
||||
{
|
||||
if (!mPairs[p.left - 'A'][p.right - 'A'])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return mPatterns.find(p) != mPatterns.end();
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
mPatterns.clear();
|
||||
for (int i = 0; i < 6; ++i)
|
||||
{
|
||||
for (int j = 0; j < 6; ++j)
|
||||
{
|
||||
mPairs[i][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// global variables
|
||||
// statistics
|
||||
unsigned bottomSize = 0;
|
||||
string bottomString;
|
||||
char pyramid[6][6]; // 0: not searched, A-F: searching, 1: finished
|
||||
PatternManager pMgr;
|
||||
// search temp
|
||||
unsigned curR, curC;
|
||||
bool found, finished;
|
||||
|
||||
class AnswerCache
|
||||
{
|
||||
private:
|
||||
std::unordered_map<string, bool> mAllowedBottomcache;
|
||||
|
||||
string wholeRowToString(unsigned rowIdx)
|
||||
{
|
||||
string s = "";
|
||||
for (int i = 0; i <= rowIdx; ++i)
|
||||
{
|
||||
s.push_back(pyramid[rowIdx][i]);
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
public:
|
||||
AnswerCache() {}
|
||||
|
||||
void setCache()
|
||||
{
|
||||
mAllowedBottomcache[wholeRowToString(curR)] = false;
|
||||
}
|
||||
|
||||
// false: not in cache, true: hit
|
||||
int getCache(int rowIdx)
|
||||
{
|
||||
string rowStr = wholeRowToString(rowIdx);
|
||||
return mAllowedBottomcache.contains(rowStr);
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
mAllowedBottomcache.clear();
|
||||
}
|
||||
};
|
||||
|
||||
AnswerCache ansCache;
|
||||
|
||||
class Initializer
|
||||
{
|
||||
public:
|
||||
// init variables and clear mMgr
|
||||
void initVariables()
|
||||
{
|
||||
// init temp
|
||||
curR = bottomSize - 2;
|
||||
curC = bottomSize - 2;
|
||||
found = 0;
|
||||
finished = 0;
|
||||
|
||||
// clear manager
|
||||
pMgr.clear();
|
||||
ansCache.clear();
|
||||
|
||||
// clear answer cache
|
||||
|
||||
// init pyramid
|
||||
for (int i = 0; i < 6; ++i)
|
||||
{
|
||||
for (int j = 0; j < 6; ++j)
|
||||
{
|
||||
pyramid[i][j] = '0';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// init bottomString and the pyramid array
|
||||
void initPyramidBottom(const string &data)
|
||||
{
|
||||
bottomString = data;
|
||||
|
||||
for (int i = 0; i < bottomSize; ++i)
|
||||
{
|
||||
pyramid[bottomSize - 1][i] = data[i];
|
||||
}
|
||||
}
|
||||
|
||||
// fill data to mMgr
|
||||
void initPattern(const vector<string> &allowed)
|
||||
{
|
||||
for (const auto &s : allowed)
|
||||
{
|
||||
pMgr.add(Pattern(s));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class Searcher
|
||||
{
|
||||
private:
|
||||
bool deltaSearchpointer(bool forward)
|
||||
{
|
||||
// forward
|
||||
if (forward)
|
||||
{
|
||||
if (curR <= 0 && curC <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (curC > 0)
|
||||
{
|
||||
--curC;
|
||||
}
|
||||
else
|
||||
{
|
||||
--curR;
|
||||
curC = curR;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// backward
|
||||
else
|
||||
{
|
||||
if (curC >= bottomSize - 2 && curR >= bottomSize - 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (curC < curR)
|
||||
{
|
||||
++curC;
|
||||
}
|
||||
else
|
||||
{
|
||||
++curR;
|
||||
curC = 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
char &curChar() { return pyramid[curR][curC]; }
|
||||
|
||||
char &leftChar() { return pyramid[curR + 1][curC]; }
|
||||
|
||||
char &rightChar() { return pyramid[curR + 1][curC + 1]; }
|
||||
|
||||
bool atTop() { return curR == curC && curC == 0; }
|
||||
|
||||
bool curValid()
|
||||
{
|
||||
return pMgr.exists(Pattern(curChar(), leftChar(), rightChar()));
|
||||
}
|
||||
|
||||
void setToNextPossibleChar()
|
||||
{
|
||||
// search end
|
||||
if (curChar() == '1')
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// search not begin
|
||||
if (curChar() == '0')
|
||||
{
|
||||
curChar() = 'A';
|
||||
if (curValid())
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
++curChar();
|
||||
|
||||
while (curChar() <= 'F' && !curValid())
|
||||
{
|
||||
++curChar();
|
||||
}
|
||||
|
||||
if (curChar() > 'F')
|
||||
{
|
||||
curChar() = '1';
|
||||
}
|
||||
}
|
||||
|
||||
void _search()
|
||||
{
|
||||
|
||||
// already found answer
|
||||
if (found || finished)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// try use cache to check if we could skip current layer
|
||||
// before we are about to start a new upper layer
|
||||
if (curC == curR && curChar() == '0')
|
||||
{
|
||||
if (ansCache.getCache(curR + 1))
|
||||
{
|
||||
deltaSearchpointer(0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setToNextPossibleChar();
|
||||
|
||||
bool isDelta;
|
||||
|
||||
// this position finished
|
||||
if (curChar() == '1')
|
||||
{
|
||||
isDelta = deltaSearchpointer(0);
|
||||
|
||||
// finished
|
||||
if (!isDelta)
|
||||
{
|
||||
finished = 1;
|
||||
}
|
||||
|
||||
// back to lower layer
|
||||
if (curC == 0)
|
||||
{
|
||||
// remember this layer of pattern doesn't work
|
||||
ansCache.setCache();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// this position not finish searching
|
||||
isDelta = deltaSearchpointer(1);
|
||||
if (!isDelta)
|
||||
{
|
||||
found = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
curChar() = '0';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
public:
|
||||
void search()
|
||||
{
|
||||
while (!found && !finished)
|
||||
{
|
||||
_search();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class Solution
|
||||
{
|
||||
public:
|
||||
bool pyramidTransition(string bottom, vector<string> &allowed)
|
||||
{
|
||||
// initialization
|
||||
bottomSize = bottom.size();
|
||||
auto initer = Initializer();
|
||||
initer.initVariables();
|
||||
initer.initPyramidBottom(bottom);
|
||||
initer.initPattern(allowed);
|
||||
|
||||
// search the answer
|
||||
auto searcher = Searcher();
|
||||
searcher.search();
|
||||
return found;
|
||||
}
|
||||
};
|
||||
```
|
||||
BIN
content/Leetcode Questions/assets/251231_another_way_of_cache.png
LFS
Normal file
BIN
content/Leetcode Questions/assets/251231_another_way_of_cache.png
LFS
Normal file
Binary file not shown.
BIN
content/Leetcode Questions/assets/251231_no_solution.png
LFS
Normal file
BIN
content/Leetcode Questions/assets/251231_no_solution.png
LFS
Normal file
Binary file not shown.
BIN
content/Leetcode Questions/assets/251231_search_direction.png
LFS
Normal file
BIN
content/Leetcode Questions/assets/251231_search_direction.png
LFS
Normal file
Binary file not shown.
BIN
content/Leetcode Questions/assets/251231_store_search_info.png
LFS
Normal file
BIN
content/Leetcode Questions/assets/251231_store_search_info.png
LFS
Normal file
Binary file not shown.
BIN
content/Leetcode Questions/assets/251231_use_cache.png
LFS
Normal file
BIN
content/Leetcode Questions/assets/251231_use_cache.png
LFS
Normal file
Binary file not shown.
6
content/Leetcode Questions/index.md
Normal file
6
content/Leetcode Questions/index.md
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
title: Leetcode Questions
|
||||
date: 2025-12-25
|
||||
---
|
||||
|
||||
Some notes about Leetcode questions.
|
||||
Reference in New Issue
Block a user