### Example Git Clone from GitHub Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/gitserver.md An illustrative command demonstrating how to clone a public repository from GitHub, highlighting the common .git naming convention for repository URLs. ```bash git clone https://github.com/youngyangyang04/NoSQLAttack.git ``` -------------------------------- ### Client: Create, Add, and Commit First File Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/gitserver.md Commands to create a new test file, stage it for commit, and then commit it to the local Git repository with an initial commit message. ```bash touch test git add test git commit -m "add test file" ``` -------------------------------- ### Client: Initialize Local Git Repository Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/gitserver.md Command to initialize a standard Git repository within the local 'world' directory, creating the necessary .git subdirectory for version control. ```bash cd world git init ``` -------------------------------- ### Create and Enter New Bare Repository Directory Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/gitserver.md Commands to create a new directory for a bare Git repository on the server, following the .git naming convention, and then navigate into it for initialization. ```bash [git@localhost git]# mkdir world.git [git@localhost git]# cd world.git ``` -------------------------------- ### Navigate to Git Home Directory Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/gitserver.md Change the current directory to the 'git' user's home directory, typically ~/git, where private Git repositories will be created and managed. ```bash cd ~/git ``` -------------------------------- ### Client: Create Local Repository Directory Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/gitserver.md Commands for the client to create a local directory named 'world' (to match the server-side repository) and change into it, preparing for local Git operations. ```bash mkdir world cd world ``` -------------------------------- ### Initialize Bare Git Repository on Server Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/gitserver.md Command to initialize an empty Git repository as a bare repository. This type of repository is ideal for server-side hosting as it does not contain a working directory. ```bash git init --bare ``` -------------------------------- ### Client: Connect to Remote and Push Initial Commit Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/gitserver.md Commands to add the private Git server as a remote named 'origin' and then push the local 'master' branch to it, establishing the connection and uploading the initial commit. ```bash git remote add origin git@git服务器端的ip:world.git git push -u origin master ``` -------------------------------- ### Switch to Git User Account Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/gitserver.md Commands to switch to the dedicated 'git' user account on the server, which is a prerequisite for managing Git repositories. Includes options for switching from root or other user accounts. ```bash su - git ``` ```bash sudo su - git ``` -------------------------------- ### Example Git Clone from GitHub Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/qita/gitserver.md An example command demonstrating how to clone a repository from GitHub, illustrating the common '.git' naming convention for repositories. ```Shell git clone https://github.com/youngyangyang04/NoSQLAttack.git ``` -------------------------------- ### Example Graph Edges and Weights Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/kamacoder/0094.城市间货物运输I-SPFA.md This snippet provides an example set of directed edges with their corresponding weights, used to illustrate the simulation process of the shortest path algorithm. Each line represents an edge in the format: `source_node destination_node weight`. ```Text 5 6 -2 1 2 1 5 3 1 2 5 2 2 4 -3 4 6 4 1 3 5 ``` -------------------------------- ### Dijkstra Problem Input and Output Example Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/kamacoder/0047.参会dijkstra堆.md This snippet provides an example of the input format for the Dijkstra problem, including the number of stations (N), roads (M), and individual road details (S, E, V). It also shows the corresponding minimum time output. ```text 7 9 1 2 1 1 3 4 2 3 2 2 4 5 3 4 2 4 5 3 2 6 4 5 7 4 6 7 9 ``` ```text 12 ``` -------------------------------- ### Complete C++ DFS Solution - Approach 2 (Process Next Node) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0841.钥匙和房间.md This is the complete C++ solution for the 'Keys and Rooms' problem using the second DFS approach. The 'canVisitAllRooms' function initializes a 'visited' array, marks room 0 as visited (as it's the starting point), starts the DFS traversal, and then verifies if all rooms were reachable. ```C++ 写法二:处理下一个要访问的节点 class Solution { private: void dfs(const vector>& rooms, int key, vector& visited) { vector keys = rooms[key]; for (int key : keys) { if (visited[key] == false) { visited[key] = true; dfs(rooms, key, visited); } } } public: bool canVisitAllRooms(vector>& rooms) { vector visited(rooms.size(), false); visited[0] = true; // 0 节点是出发节点,一定被访问过 dfs(rooms, 0, visited); //检查是否都访问到了 for (int i : visited) { if (i == false) return false; } return true; } }; ``` -------------------------------- ### Input and Output Example for Redundant Connection II Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/kamacoder/0109.冗余连接II.md This snippet shows an example input for the problem and its corresponding expected output. The input describes a graph with 3 nodes and 3 edges. Removing the edge 2 -> 3 results in a valid directed tree. ```Text Input: 3 1 2 1 3 2 3 Output: 2 3 ``` -------------------------------- ### Build and Run KV Storage Engine Demo Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/kvstore.md Commands to compile the `main.cpp` demo application and execute the resulting binary. This process creates the executable in the `bin` directory. ```Shell make ./bin/main ``` -------------------------------- ### Example Usage of Custom Linked List in C Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0707.设计链表.md Illustrates the typical sequence of operations for instantiating and using the `MyLinkedList` functions, including creation, getting values, adding elements, deleting elements, and finally freeing the allocated memory. ```C MyLinkedList* obj = myLinkedListCreate(); int param_1 = myLinkedListGet(obj, index); myLinkedListAddAtHead(obj, val); myLinkedListAddAtTail(obj, val); myLinkedListAddAtIndex(obj, index, val); myLinkedListDeleteAtIndex(obj, index); myLinkedListFree(obj); ``` -------------------------------- ### Find Itinerary using Backtracking (Python, Dictionary) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0332.重新安排行程.md This Python solution uses a dictionary to represent the graph of flights. It sorts destinations alphabetically for each departure airport and employs a DFS-based backtracking approach to find a valid itinerary starting from 'JFK'. The result is built in reverse order during the DFS traversal and then reversed at the end to get the correct sequence. ```python class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: self.adj = {} # sort by the destination alphabetically # 根据航班每一站的重点字母顺序排序 tickets.sort(key=lambda x:x[1]) # get all possible connection for each destination # 罗列每一站的下一个可选项 for u,v in tickets: if u in self.adj: self.adj[u].append(v) else: self.adj[u] = [v] # 从JFK出发 self.result = [] self.dfs("JFK") # start with JFK return self.result[::-1] # reverse to get the result def dfs(self, s): # if depart city has flight and the flight can go to another city while s in self.adj and len(self.adj[s]) > 0: # 找到s能到哪里,选能到的第一个机场 v = self.adj[s][0] # we go to the 1 choice of the city # 在之后的可选项机场中去掉这个机场 self.adj[s].pop(0) # get rid of this choice since we used it # 从当前的新出发点开始 self.dfs(v) # we start from the new airport self.result.append(s) # after append, it will back track to last node, thus the result list is in reversed order ``` -------------------------------- ### Example Usage: Go Binary Tree Construction and Printing Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/ACM模式如何构建二叉树.md This Go snippet provides a `main` function demonstrating the end-to-end usage of the `constructBinaryTree` and `printBinaryTree` functions. It initializes a sample array, constructs the corresponding binary tree, and then prints its level-order representation to the console. ```Go func main() { array := []int{4, 1, 6, 0, 2, 5, 7, -1, -1, -1, 3, -1, -1, -1, 8} root := constructBinaryTree(array) printBinaryTree(root, len(array)) } ``` -------------------------------- ### Erase Overlap Intervals: Greedy Solution by Left Boundary Sort Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0435.无重叠区间.md This alternative greedy strategy sorts the intervals by their left (start) boundaries. Two variations are shown: one iterating backward from the end, and another iterating forward, adjusting the 'right' boundary to minimize overlaps. The goal is to find the maximum number of non-overlapping intervals, and subtract this from the total to get the minimum to remove. ```js var eraseOverlapIntervals = function(intervals) { // 按照左边界升序排列 intervals.sort((a, b) => a[0] - b[0]) let count = 1 let end = intervals[intervals.length - 1][0] // 倒序遍历,对单个区间来说,左边界越大越好,因为给前面区间的空间越大 for(let i = intervals.length - 2; i >= 0; i--) { if(intervals[i][1] <= end) { count++ end = intervals[i][0] } } // count 记录的是最大非重复区间的个数 return intervals.length - count } ``` ```typescript function eraseOverlapIntervals(intervals: number[][]): number { if (intervals.length === 0) return 0; intervals.sort((a, b) => a[0] - b[0]); let right: number = intervals[0][1]; let tempInterval: number[]; let resCount: number = 0; for (let i = 1, length = intervals.length; i < length; i++) { tempInterval = intervals[i]; if (tempInterval[0] >= right) { // 未重叠 right = tempInterval[1]; } else { // 有重叠,移除当前interval和前一个interval中右边界更大的那个 right = Math.min(right, tempInterval[1]); resCount++; } } return resCount; }; ``` -------------------------------- ### Java Dynamic Programming Solution for Longest Continuous Increasing Subsequence Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0674.最长连续递增序列.md This Java snippet implements the Dynamic Programming approach. Similar to the C++ version, dp[i] stores the length of the continuous increasing subsequence ending at i. It notes a slight difference in loop indexing (i starts from 0) compared to the C++ example, leading to i+1 offsets in some places. The result is the maximum value found in the dp array. ```Java /** * 1.dp[i] 代表当前下标最大连续值 * 2.递推公式 if(nums[i+1]>nums[i]) dp[i+1] = dp[i]+1 * 3.初始化 都为1 * 4.遍历方向,从其那往后 * 5.结果推导 。。。。 * @param nums * @return */ public static int findLengthOfLCIS(int[] nums) { int[] dp = new int[nums.length]; for (int i = 0; i < dp.length; i++) { dp[i] = 1; } int res = 1; //可以注意到,這邊的 i 是從 0 開始,所以會出現和卡哥的C++ code有差異的地方,在一些地方會看到有 i + 1 的偏移。 for (int i = 0; i < nums.length - 1; i++) { if (nums[i + 1] > nums[i]) { dp[i + 1] = dp[i] + 1; } res = res > dp[i + 1] ? res : dp[i + 1]; } return res; } ``` -------------------------------- ### Client: Initialize Local Git Repository Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/qita/gitserver.md Command to initialize a new Git repository in the client's local 'world' directory, preparing it for version control. ```Shell cd world git init ``` -------------------------------- ### Traverse Matrix in Spiral Order (Go, Layer-by-Layer) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0054.螺旋矩阵.md This Go solution implements the spiral matrix traversal using a layer-by-layer approach. It defines `startx`, `starty` for the current layer's top-left corner and `offset` to control the length of each side. It includes a helper function `min` and handles odd-sized matrices to correctly fill the central elements. ```go func spiralOrder(matrix [][]int) []int { rows := len(matrix) if rows == 0 { return []int{} } columns := len(matrix[0]) if columns == 0 { return []int{} } res := make([]int, rows * columns) startx, starty := 0, 0 // 定义每循环一个圈的起始位置 loop := min(rows, columns) / 2 mid := min(rows, columns) / 2 count := 0 // 用来给矩阵中每一个空格赋值 offset := 1 // 每一圈循环,需要控制每一条边遍历的长度 for loop > 0 { i, j := startx, starty // 模拟填充上行从左到右(左闭右开) for ; j < starty + columns - offset; j++ { res[count] = matrix[startx][j] count++ } // 模拟填充右列从上到下(左闭右开) for ; i < startx + rows - offset; i++ { res[count] = matrix[i][j] count++ } // 模拟填充下行从右到左(左闭右开) for ; j > starty; j-- { res[count] = matrix[i][j] count++ } // 模拟填充左列从下到上(左闭右开) for ; i > startx; i-- { res[count] = matrix[i][starty] count++ } // 第二圈开始的时候,起始位置要各自加1, 例如:第一圈起始位置是(0, 0),第二圈起始位置是(1, 1) startx++ starty++ // offset 控制每一圈里每一条边遍历的长度 offset += 2 loop-- } // 如果min(rows, columns)为奇数的话,需要单独给矩阵最中间的位置赋值 if min(rows, columns) % 2 == 1 { if rows > columns { for i := mid; i < mid + rows - columns + 1; i++ { res[count] = matrix[i][mid] count++ } } else { for i := mid; i < mid + columns - rows + 1; i++ { res[count] = matrix[mid][i] count++ } } } return res } func min(x, y int) int { if x < y { return x } return y } ``` -------------------------------- ### C++ Program to Measure Optimized Recursive Fibonacci Performance Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/递归算法的时间与空间复杂度分析.md This C++ program measures the execution time of the optimized recursive Fibonacci function (`fibonacci_3`). It includes the necessary setup for time measurement and input, similar to the previous example. The `time_consumption` function calls `fibonacci_3` with initial values (1, 1) and the input `n`, then reports the elapsed time, demonstrating the significant performance improvement over the classic version. ```CPP #include #include #include using namespace std; using namespace chrono; int fibonacci_3(int first, int second, int n) { if (n <= 0) { return 0; } if (n < 3) { return 1; } else if (n == 3) { return first + second; } else { return fibonacci_3(second, first + second, n - 1); } } void time_consumption() { int n; while (cin >> n) { milliseconds start_time = duration_cast( system_clock::now().time_since_epoch() ); fibonacci_3(1, 1, n); milliseconds end_time = duration_cast( system_clock::now().time_since_epoch() ); cout << milliseconds(end_time).count() - milliseconds(start_time).count() <<" ms"<< endl; } } int main() { time_consumption(); return 0; } ``` -------------------------------- ### Solve Gas Station Problem with Optimized Greedy Algorithm (Method Two) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0134.加油站.md This optimized greedy approach efficiently finds the starting gas station. It maintains a `curSum` to track the balance of the current segment and `totalSum` for the overall balance. If `curSum` drops below zero, it indicates that the current segment is not a valid starting point, so the `start` index is updated to the next station, and `curSum` is reset. The final `start` index is returned if the `totalSum` is non-negative, indicating a complete circuit is possible. ```Scala object Solution { def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = { var curSum = 0 var totalSum = 0 var start = 0 for (i <- gas.indices) { curSum += (gas(i) - cost(i)) totalSum += (gas(i) - cost(i)) if (curSum < 0) { start = i + 1 // 起始位置更新 curSum = 0 // curSum从0开始 } } if (totalSum < 0) return -1 // 说明怎么走不可能跑一圈 start } } ``` ```C# // 贪心算法,方法二 public class Solution { public int CanCompleteCircuit(int[] gas, int[] cost) { int curSum = 0, totalSum = 0, start = 0; for (int i = 0; i < gas.Length; i++) { curSum += gas[i] - cost[i]; totalSum += gas[i] - cost[i]; if (curSum < 0) { start = i + 1; curSum = 0; } } if (totalSum < 0) return -1; return start; } } ``` -------------------------------- ### MyQueue Class Basic Usage Example (C++) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0232.用栈实现队列.md Illustrates the fundamental operations of the MyQueue class, demonstrating how elements are pushed, peeked, popped, and how the queue's emptiness is checked, mimicking standard queue behavior. ```cpp MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false ``` -------------------------------- ### C++ TreeNode Instantiation with Constructor Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/周总结/20200927二叉树周末总结.md Demonstrates how to create a new `TreeNode` object and initialize its value using the provided constructor, simplifying node creation. ```CPP TreeNode* a = new TreeNode(9); ``` -------------------------------- ### Solve Gas Station Problem with Greedy Algorithm (Method One, Scala) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0134.加油站.md This Scala solution applies a greedy algorithm to find the optimal starting point for the gas station problem. It calculates the total sum of gas minus cost and tracks the minimum cumulative sum encountered. Based on these values, it determines the starting index. This method efficiently handles three main cases: when the total gas is insufficient, when starting from index 0 is always valid, and when a specific starting point is needed to overcome a deficit. ```Scala object Solution { def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = { var curSum = 0 var min = Int.MaxValue for (i <- gas.indices) { var rest = gas(i) - cost(i) curSum += rest min = math.min(min, curSum) } if (curSum < 0) return -1 // 情况1: gas的总和小于cost的总和,不可能到达终点 if (min >= 0) return 0 // 情况2: 最小值>=0,从0号出发可以直接到达 // 情况3: min为负值,从后向前看,能把min填平的节点就是出发节点 for (i <- gas.length - 1 to 0 by -1) { var rest = gas(i) - cost(i) min += rest if (min >= 0) return i } -1 } } ``` -------------------------------- ### Initialize Bare Git Repository on Server Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/qita/gitserver.md Command to initialize a bare Git repository, which is suitable for server-side hosting and does not contain a working tree. ```Shell git init --bare ``` -------------------------------- ### Client: Create, Add, and Commit Test File Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/qita/gitserver.md Commands to create a new test file, add it to the Git staging area, and commit it to the local repository with a descriptive message. ```Shell touch test git add test git commit -m "add test file" ``` -------------------------------- ### Solve Gas Station Problem with Brute Force (Scala) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0134.加油站.md This Scala implementation uses a brute-force approach to find a valid starting gas station. It iterates through each possible station as a starting point and simulates the journey around the circuit. If the journey can be completed without running out of fuel, that starting index is returned. This method can be inefficient for large inputs due to its O(N^2) time complexity. ```Scala object Solution { def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = { for (i <- cost.indices) { var rest = gas(i) - cost(i) var index = (i + 1) % cost.length // index为i的下一个节点 while (rest > 0 && i != index) { rest += (gas(index) - cost(index)) index = (index + 1) % cost.length } if (rest >= 0 && index == i) return i } -1 } } ``` -------------------------------- ### Greedy Solution (Method 2) for Gas Station Problem Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0134.加油站.md This optimized greedy solution identifies the starting station by tracking the current sum of gas differences. If the current sum drops below zero, it means the current segment is not a valid starting point, so the starting point is reset to the next station, and the current sum is reset to zero. The total sum is also tracked to ensure a circuit is possible. This method has a time complexity of O(n). ```JavaScript var canCompleteCircuit = function(gas, cost) { const gasLen = gas.length let start = 0 let curSum = 0 let totalSum = 0 for(let i = 0; i < gasLen; i++) { curSum += gas[i] - cost[i] totalSum += gas[i] - cost[i] if(curSum < 0) { curSum = 0 start = i + 1 } } if(totalSum < 0) return -1 return start }; ``` ```TypeScript function canCompleteCircuit(gas: number[], cost: number[]): number { let total: number = 0; let curGas: number = 0; let tempDiff: number = 0; let resIndex: number = 0; for (let i = 0, length = gas.length; i < length; i++) { tempDiff = gas[i] - cost[i]; total += tempDiff; curGas += tempDiff; if (curGas < 0) { resIndex = i + 1; curGas = 0; } } if (total < 0) return -1; return resIndex; }; ``` ```Rust impl Solution { pub fn can_complete_circuit(gas: Vec, cost: Vec) -> i32 { let mut cur_sum = 0; let mut total_sum = 0; let mut start = 0; for i in 0..gas.len() { cur_sum += gas[i] - cost[i]; total_sum += gas[i] - cost[i]; if cur_sum < 0 { start = i + 1; cur_sum = 0; } } if total_sum < 0 { return -1; } start as i32 } } ``` ```C int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){ int curSum = 0; int totalSum = 0; int start = 0; int i; for(i = 0; i < gasSize; ++i) { // 当前i站中加油量与耗油量的差 int diff = gas[i] - cost[i]; curSum += diff; totalSum += diff; // 若0到i的加油量都为负,则开始位置应为i+1 if(curSum < 0) { curSum = 0; // 当i + 1 == gasSize时,totalSum < 0(此时i为gasSize - 1),油车不可能返回原点 start = i + 1; } } // 若总和小于0,加油车无论如何都无法返回原点。返回-1 if(totalSum < 0) return -1; return start; } ``` -------------------------------- ### Create and Enter Git Repository Directory on Server Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/qita/gitserver.md Commands to create a new directory named 'world.git' for the private Git repository and then navigate into it on the server. ```Shell mkdir world.git cd world.git ``` -------------------------------- ### Greedy Algorithm (Approach 2) for Gas Station Problem (C++) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0134.加油站.md This is a more standard greedy approach. It calculates the cumulative sum of (gas[i] - cost[i]). If the current cumulative sum (curSum) drops below zero, it means that no starting point from the beginning up to the current index 'i' can complete the journey to 'i'. Therefore, the potential starting point is reset to 'i + 1', and curSum is reset to 0. If the total sum of (gas[i] - cost[i]) is negative, no solution exists. Otherwise, the last determined 'start' index is the solution. ```C++ class Solution { public: int canCompleteCircuit(vector& gas, vector& cost) { int curSum = 0; int totalSum = 0; int start = 0; for (int i = 0; i < gas.size(); i++) { curSum += gas[i] - cost[i]; totalSum += gas[i] - cost[i]; if (curSum < 0) { // 当前累加rest[i]和 curSum一旦小于0 start = i + 1; // 起始位置更新为i+1 curSum = 0; // curSum从0开始 } } if (totalSum < 0) return -1; // 说明怎么走都不可能跑一圈了 return start; } }; ``` -------------------------------- ### Client: Create and Navigate to Local Repository Directory Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/qita/gitserver.md Commands for the client to create a local directory named 'world' and change into it, mirroring the server repository name for clarity. ```Shell mkdir world cd world ``` -------------------------------- ### Go: Palindrome Partitioning with Basic Backtracking Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0131.分割回文串.md This Go snippet implements the Palindrome Partitioning problem using a standard backtracking (DFS) algorithm. It recursively explores all possible partitions, checking if each substring is a palindrome using a dedicated helper function. The `path` slice stores the current partition, and `res` collects all valid partitions. ```Go var ( path []string // 放已经回文的子串 res [][]string ) func partition(s string) [][]string { path, res = make([]string, 0), make([][]string, 0) dfs(s, 0) return res } func dfs(s string, start int) { if start == len(s) { // 如果起始位置等于s的大小,说明已经找到了一组分割方案了 tmp := make([]string, len(path)) copy(tmp, path) res = append(res, tmp) return } for i := start; i < len(s); i++ { str := s[start : i+1] if isPalindrome(str) { // 是回文子串 path = append(path, str) dfs(s, i+1) // 寻找i+1为起始位置的子串 path = path[:len(path)-1] // 回溯过程,弹出本次已经添加的子串 } } } func isPalindrome(s string) bool { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { if s[i] != s[j] { return false } } return true } ``` -------------------------------- ### C++ Initialization for Itinerary Reconstruction Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0332.重新安排行程.md This C++ snippet demonstrates the initialization process for the itinerary reconstruction problem. It populates the `targets` map by iterating through the input `tickets` to count the occurrences of each flight path. Additionally, it initializes the `result` vector by adding 'JFK' as the starting airport. ```cpp for (const vector& vec : tickets) { targets[vec[0]][vec[1]]++; // 记录映射关系 } result.push_back("JFK"); // 起始机场 ``` -------------------------------- ### A* Algorithm Implementation for Knight's Shortest Path Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/kamacoder/0126.骑士的攻击astar.md This C++ implementation demonstrates the A* algorithm, an optimized version of BFS, for solving the knight's shortest path problem. It leverages a priority queue and a heuristic function (Euclidean distance, specifically squared Euclidean distance for precision) to guide the search towards the target, significantly reducing the number of visited nodes compared to pure BFS. The algorithm calculates a 'cost' F = G + H for each node, where G is the actual cost from the start and H is the estimated cost to the target, prioritizing nodes with the lowest F value. ```C++ #include #include #include using namespace std; int moves[1001][1001]; int dir[8][2]={-2,-1,-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2}; int b1, b2; // F = G + H // G = 从起点到该节点路径消耗 // H = 该节点到终点的预估消耗 struct Knight{ int x,y; int g,h,f; bool operator < (const Knight & k) const{ // 重载运算符, 从小到大排序 return k.f < f; } }; priority_queue que; int Heuristic(const Knight& k) { // 欧拉距离 return (k.x - b1) * (k.x - b1) + (k.y - b2) * (k.y - b2); // 统一不开根号,这样可以提高精度 } void astar(const Knight& k) { Knight cur, next; que.push(k); while(!que.empty()) { cur=que.top(); que.pop(); if(cur.x == b1 && cur.y == b2) break; for(int i = 0; i < 8; i++) { next.x = cur.x + dir[i][0]; next.y = cur.y + dir[i][1]; if(next.x < 1 || next.x > 1000 || next.y < 1 || next.y > 1000) continue; if(!moves[next.x][next.y]) { moves[next.x][next.y] = moves[cur.x][cur.y] + 1; // 开始计算F next.g = cur.g + 5; // 统一不开根号,这样可以提高精度,马走日,1 * 1 + 2 * 2 = 5 next.h = Heuristic(next); next.f = next.g + next.h; que.push(next); } } } } int main() { int n, a1, a2; cin >> n; while (n--) { cin >> a1 >> a2 >> b1 >> b2; memset(moves,0,sizeof(moves)); Knight start; start.x = a1; start.y = a2; start.g = 0; start.h = Heuristic(start); start.f = start.g + start.h; astar(start); while(!que.empty()) que.pop(); // 队列清空 cout << moves[b1][b2] << endl; } return 0; } ``` -------------------------------- ### Complete C++ Example: Binary Tree Construction and Level-Order Print Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/ACM模式如何构建二叉树.md This full C++ program demonstrates the process of constructing a binary tree from an array and then printing its contents using level-order traversal. It defines the `TreeNode` struct, includes the `construct_binary_tree` function, and adds a `print_binary_tree` function that outputs the tree's structure, using `-1` to represent null nodes. The `main` function provides a complete test case. ```CPP #include #include #include using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; // 根据数组构造二叉树 TreeNode* construct_binary_tree(const vector& vec) { vector vecTree (vec.size(), NULL); TreeNode* root = NULL; for (int i = 0; i < vec.size(); i++) { TreeNode* node = NULL; if (vec[i] != -1) node = new TreeNode(vec[i]); vecTree[i] = node; if (i == 0) root = node; } for (int i = 0; i * 2 + 1 < vec.size(); i++) { if (vecTree[i] != NULL) { vecTree[i]->left = vecTree[i * 2 + 1]; if(i * 2 + 2 < vec.size()) vecTree[i]->right = vecTree[i * 2 + 2]; } } return root; } // 层序打印打印二叉树 void print_binary_tree(TreeNode* root) { queue que; if (root != NULL) que.push(root); vector> result; while (!que.empty()) { int size = que.size(); vector vec; for (int i = 0; i < size; i++) { TreeNode* node = que.front(); que.pop(); if (node != NULL) { vec.push_back(node->val); que.push(node->left); que.push(node->right); } // 这里的处理逻辑是为了把null节点打印出来,用-1 表示null else vec.push_back(-1); } result.push_back(vec); } for (int i = 0; i < result.size(); i++) { for (int j = 0; j < result[i].size(); j++) { cout << result[i][j] << " "; } cout << endl; } } int main() { // 注意本代码没有考虑输入异常数据的情况 // 用 -1 来表示null vector vec = {4,1,6,0,2,5,7,-1,-1,-1,3,-1,-1,-1,8}; TreeNode* root = construct_binary_tree(vec); print_binary_tree(root); } ``` -------------------------------- ### Greedy Solution (Method 1) for Gas Station Problem Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0134.加油站.md This greedy approach determines the starting station by analyzing the cumulative sum of gas differences. It first checks if the total gas is sufficient. If so, it finds the station that can 'fill up' the minimum cumulative deficit, which becomes the starting point. This method has a time complexity of O(n). ```JavaScript var canCompleteCircuit = function(gas, cost) { let curSum = 0 let min = Infinity for(let i = 0; i < gas.length; i++) { let rest = gas[i] - cost[i] curSum += rest if(curSum < min) { min = curSum } } if(curSum < 0) return -1 //1.总油量 小于 总消耗量 if(min >= 0) return 0 //2. 说明油箱里油没断过 //3. 从后向前,看哪个节点能这个负数填平,能把这个负数填平的节点就是出发节点 for(let i = gas.length -1; i >= 0; i--) { let rest = gas[i] - cost[i] min += rest if(min >= 0) { return i } } return -1 } ``` ```Rust impl Solution { pub fn can_complete_circuit(gas: Vec, cost: Vec) -> i32 { let mut cur_sum = 0; let mut min = i32::MAX; for i in 0..gas.len() { let rest = gas[i] - cost[i]; cur_sum += rest; if cur_sum < min { min = cur_sum; } } if cur_sum < 0 { return -1; } if min > 0 { return 0; } for i in (0..gas.len()).rev() { let rest = gas[i] - cost[i]; min += rest; if min >= 0 { return i as i32; } } -1 } } ``` ```C int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){ int curSum = 0; int i; int min = INT_MAX; //遍历整个数组。计算出每站的用油差。并将其与最小累加量比较 for(i = 0; i < gasSize; i++) { int diff = gas[i] - cost[i]; curSum += diff; if(curSum < min) min = curSum; } //若汽油总数为负数,代表无法跑完一环。返回-1 if(curSum < 0) return -1; //若min大于等于0,说明每一天加油量比用油量多。因此从0出发即可 if(min >= 0) return 0; //若累加最小值为负,则找到一个非零元素(加油量大于出油量)出发。返回坐标 for(i = gasSize - 1; i >= 0; i--) { min+=(gas[i]-cost[i]); if(min >= 0) return i; } //逻辑上不会返回这个0 return 0; } ``` -------------------------------- ### Gas Station: Brute Force Solution in Python Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0134.加油站.md This snippet presents a brute-force approach to solve the Gas Station problem. It iterates through each possible gas station as a starting point and simulates the entire circular journey. If the car can complete the circuit with non-negative fuel, that starting point is returned. This method is straightforward but less efficient for larger inputs. ```python class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: for i in range(len(cost)): rest = gas[i] - cost[i] # 记录剩余油量 index = (i + 1) % len(cost) # 下一个加油站的索引 while rest > 0 and index != i: # 模拟以i为起点行驶一圈(如果有rest==0,那么答案就不唯一了) rest += gas[index] - cost[index] # 更新剩余油量 index = (index + 1) % len(cost) # 更新下一个加油站的索引 if rest >= 0 and index == i: # 如果以i为起点跑一圈,剩余油量>=0,并且回到起始位置 return i # 返回起始位置i return -1 # 所有起始位置都无法环绕一圈,返回-1 ``` -------------------------------- ### Minimum Camera Cover using Dynamic Programming (Go) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0968.监控二叉树.md This Go solution approaches the problem using a dynamic programming-like recursive function `dfs`. For each node, `dfs` returns three values: `a` (cost if current node has a camera), `b` (cost if current node is covered by a child or itself), and `c` (cost if current node is covered by its parent). It uses `math.MaxInt64 / 2` as infinity for base cases. ```Go const inf = math.MaxInt64 / 2 func minCameraCover(root *TreeNode) int { var dfs func(*TreeNode) (a, b, c int) dfs = func(node *TreeNode) (a, b, c int) { if node == nil { return inf, 0, 0 } lefta, leftb, leftc := dfs(node.Left) righta, rightb, rightc := dfs(node.Right) a = leftc + rightc + 1 b = min(a, min(lefta+rightb, righta+leftb)) c = min(a, leftb+rightb) return } _, ans, _ := dfs(root) return ans } func min(a, b int) int { if a <= b { return a } return b } ``` -------------------------------- ### Optimized Solution: Minimum Camera Cover (Version 2) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0968.监控二叉树.md This is a more concise C++ implementation of the minimum camera cover problem, refactored from Version 1. It achieves the same logic by using `else if` and `else` statements to streamline the state transition conditions, making the code shorter while maintaining functionality. It's important to understand Version 1 first for clarity. ```CPP // 版本二 class Solution { private: int result; int traversal(TreeNode* cur) { if (cur == NULL) return 2; int left = traversal(cur->left); // 左 int right = traversal(cur->right); // 右 if (left == 2 && right == 2) return 0; else if (left == 0 || right == 0) { result++; return 1; } else return 2; } public: int minCameraCover(TreeNode* root) { result = 0; if (traversal(root) == 0) { // root 无覆盖 result++; } return result; } }; ``` -------------------------------- ### TypeScript Singly Linked List: MyLinkedList Class Structure and Get Method Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0707.设计链表.md Initializes the `MyLinkedList` class, managing the size, head, and tail of the singly linked list. The `get` method retrieves the value of the node at a specified index, returning -1 for invalid indices. The private `getNode` helper efficiently locates a node by index. ```TypeScript class MyLinkedList { // 记录链表长度 private size: number; private head: ListNode | null; private tail: ListNode | null; constructor() { this.size = 0; this.head = null; this.tail = null; } // 获取链表中第 index个节点的值 get(index: number): number { // 索引无效的情况 if (index < 0 || index >= this.size) { return -1; } let curNode = this.getNode(index); // 这里在前置条件下,理论上不会出现 null的情况 return curNode.val; } // 获取指定 Node节点 private getNode(index: number): ListNode { // 这里不存在没办法获取到节点的情况,都已经在前置方法做过判断 // 创建虚拟头节点 let curNode: ListNode = new ListNode(0, this.head); for (let i = 0; i <= index; i++) { // 理论上不会出现 null curNode = curNode.next!; } return curNode; } } ``` -------------------------------- ### Run KV Storage Engine Performance Stress Test Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/前序/kvstore.md Executes a shell script to conduct a performance stress test on the KV storage engine, measuring its throughput (QPS) for read and write operations under various data scales. ```Shell sh stress_test_start.sh ``` -------------------------------- ### Brute Force Solution for Gas Station Problem (C++) Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0134.加油站.md This approach iterates through each gas station as a potential starting point and simulates the entire circular journey. It checks if the car can complete a full circle without running out of fuel. The simulation uses a while loop to handle the circular traversal. If a valid starting point is found, its index is returned; otherwise, -1 is returned. ```C++ class Solution { public: int canCompleteCircuit(vector& gas, vector& cost) { for (int i = 0; i < cost.size(); i++) { int rest = gas[i] - cost[i]; // 记录剩余油量 int index = (i + 1) % cost.size(); while (rest > 0 && index != i) { // 模拟以i为起点行驶一圈(如果有rest==0,那么答案就不唯一了) rest += gas[index] - cost[index]; index = (index + 1) % cost.size(); } // 如果以i为起点跑一圈,剩余油量>=0,返回该起始位置 if (rest >= 0 && index == i) return i; } return -1; } }; ``` -------------------------------- ### Go Circular Doubly Linked List Implementation Source: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0707.设计链表.md This Go code implements a circular doubly linked list (`MyLinkedList`) using a dummy node. It provides methods for initialization (`Constructor`), getting a node's value by index (`Get`), adding nodes at the head (`AddAtHead`), and tail (`AddAtTail`). The list maintains `Next` and `Pre` pointers for bi-directional traversal and circularity. ```Go //循环双链表 type MyLinkedList struct { dummy *Node } type Node struct { Val int Next *Node Pre *Node } //仅保存哑节点,pre-> rear, next-> head /** Initialize your data structure here. */ func Constructor() MyLinkedList { rear := &Node{ Val: -1, Next: nil, Pre: nil, } rear.Next = rear rear.Pre = rear return MyLinkedList{rear} } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ func (this *MyLinkedList) Get(index int) int { head := this.dummy.Next //head == this, 遍历完全 for head != this.dummy && index > 0 { index-- head = head.Next } //否则, head == this, 索引无效 if 0 != index { return -1 } return head.Val } /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ func (this *MyLinkedList) AddAtHead(val int) { dummy := this.dummy node := &Node{ Val: val, //head.Next指向原头节点 Next: dummy.Next, //head.Pre 指向哑节点 Pre: dummy, } //更新原头节点 dummy.Next.Pre = node //更新哑节点 dummy.Next = node //以上两步不能反 } /** Append a node of value val to the last element of the linked list. */ func (this *MyLinkedList) AddAtTail(val int) { dummy := this.dummy rear := &Node{ Val: val, //rear.Next = dummy(哑节点) Next: dummy, //rear.Pre = ori_rear Pre: dummy.Pre, } //ori_rear.Next = rear dummy.Pre.Next = rear //update dummy dummy.Pre = rear //以上两步不能反 } /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ ```