Skip to content

Commit db8ea90

Browse files
committed
add more solutions
1 parent bbd8d92 commit db8ea90

File tree

180 files changed

+16424
-262
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

180 files changed

+16424
-262
lines changed

c#/01_matrix.md

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,51 +8,39 @@
88
// Space Complexity: O(m * n), for the queue and distance matrix
99
using System.Collections.Generic;
1010

11-
public class Solution
12-
{
13-
public int[][] UpdateMatrix(int[][] mat)
14-
{
11+
public class Solution {
12+
public int[][] UpdateMatrix(int[][] mat) {
1513
int rows = mat.Length;
1614
int cols = mat[0].Length;
1715
int[][] distances = new int[rows][];
1816
bool[][] visited = new bool[rows][];
1917
Queue<int[]> queue = new Queue<int[]>();
2018

21-
// Step 1: Initialize the queue with all '0' cells and mark them as visited
22-
for (int i = 0; i < rows; i++)
23-
{
19+
for (int i = 0; i < rows; i++) {
2420
distances[i] = new int[cols];
2521
visited[i] = new bool[cols];
26-
for (int j = 0; j < cols; j++)
27-
{
28-
if (mat[i][j] == 0)
29-
{
22+
}
23+
24+
// Step 1: Initialize the queue with all '0' cells and mark them as visited
25+
for (int i = 0; i < rows; i++) {
26+
for (int j = 0; j < cols; j++) {
27+
if (mat[i][j] == 0) {
3028
queue.Enqueue(new int[] { i, j });
3129
visited[i][j] = true;
3230
}
3331
}
3432
}
3533

3634
// Step 2: Perform BFS to calculate distances
37-
int[][] directions = new int[][]
38-
{
39-
new int[] { 0, 1 },
40-
new int[] { 1, 0 },
41-
new int[] { 0, -1 },
42-
new int[] { -1, 0 }
43-
};
44-
45-
while (queue.Count > 0)
46-
{
35+
int[][] directions = new int[][] { new int[] { 0, 1 }, new int[] { 1, 0 }, new int[] { 0, -1 }, new int[] { -1, 0 } };
36+
while (queue.Count > 0) {
4737
int[] current = queue.Dequeue();
48-
foreach (int[] dir in directions)
49-
{
38+
foreach (var dir in directions) {
5039
int newRow = current[0] + dir[0];
5140
int newCol = current[1] + dir[1];
5241

5342
// Check bounds and if the cell is not visited
54-
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && !visited[newRow][newCol])
55-
{
43+
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && !visited[newRow][newCol]) {
5644
distances[newRow][newCol] = distances[current[0]][current[1]] + 1;
5745
queue.Enqueue(new int[] { newRow, newCol });
5846
visited[newRow][newCol] = true;

c#/add_two_numbers.md

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,41 @@
1-
# add_two_numbers.md
1+
# [2. Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)
2+
3+
## Approach: Iterative Solution with Carry
4+
5+
### Solution
6+
csharp
7+
```csharp
8+
// Time Complexity: O(max(m, n)), where m and n are the lengths of the two lists
9+
// Space Complexity: O(max(m, n)), for the new linked list
10+
public class Solution {
11+
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
12+
ListNode dummy = new ListNode(0); // Dummy node to simplify the process
13+
ListNode current = dummy; // Pointer to the current node in the result list
14+
int carry = 0; // Store carry from the addition
15+
16+
// Traverse both lists
17+
while (l1 != null || l2 != null || carry != 0) {
18+
int sum = carry; // Start with the carry
19+
20+
// Add values from l1 and l2 if they exist
21+
if (l1 != null) {
22+
sum += l1.val;
23+
l1 = l1.next;
24+
}
25+
if (l2 != null) {
26+
sum += l2.val;
27+
l2 = l2.next;
28+
}
29+
30+
// Calculate new carry and the digit to store
31+
carry = sum / 10;
32+
current.next = new ListNode(sum % 10); // Store the last digit of the sum
33+
current = current.next; // Move to the next node
34+
}
35+
36+
return dummy.next; // Skip the dummy node
37+
}
38+
}
39+
```
40+
241

c#/basic_calculator_2.md

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,54 @@
1-
# basic_calculator_2.md
1+
# [227. Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/)
2+
3+
## Approach: Using a Stack for Intermediate Results
4+
5+
### Solution
6+
csharp
7+
```csharp
8+
// Time Complexity: O(n)
9+
// Space Complexity: O(n)
10+
using System;
11+
using System.Collections.Generic;
12+
13+
public class Solution {
14+
public int Calculate(string s) {
15+
Stack<int> stack = new Stack<int>();
16+
int currentNumber = 0;
17+
char operation = '+'; // Default operation is addition
18+
19+
for (int i = 0; i < s.Length; i++) {
20+
char c = s[i];
21+
22+
// Build the current number
23+
if (char.IsDigit(c)) {
24+
currentNumber = currentNumber * 10 + (c - '0');
25+
}
26+
27+
// Process operators and the last number
28+
if (!char.IsDigit(c) && c != ' ' || i == s.Length - 1) {
29+
if (operation == '+') {
30+
stack.Push(currentNumber);
31+
} else if (operation == '-') {
32+
stack.Push(-currentNumber);
33+
} else if (operation == '*') {
34+
stack.Push(stack.Pop() * currentNumber);
35+
} else if (operation == '/') {
36+
stack.Push(stack.Pop() / currentNumber);
37+
}
38+
39+
operation = c; // Update the operation
40+
currentNumber = 0; // Reset the current number
41+
}
42+
}
43+
44+
// Sum up all the values in the stack
45+
int result = 0;
46+
while (stack.Count > 0) {
47+
result += stack.Pop();
48+
}
49+
50+
return result;
51+
}
52+
}
53+
```
254

c#/binary_tree_cameras.md

Lines changed: 107 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,108 @@
1-
# binary_tree_cameras.md
1+
2+
# 968. [Binary Tree Cameras](https://leetcode.com/problems/binary-tree-cameras/)
3+
4+
## Approach 1: Greedy Approach with Recursion
5+
6+
### Solution
7+
csharp
8+
```csharp
9+
// Time Complexity: O(n)
10+
// Space Complexity: O(h) where h is the height of the tree (recursion stack)
11+
public class Solution {
12+
private int cameras = 0;
13+
14+
public int MinCameraCover(TreeNode root) {
15+
// If root returns 0, it means it needs a camera
16+
return Dfs(root) == 0 ? cameras + 1 : cameras;
17+
}
18+
19+
// Helper function for recursive traversal
20+
private int Dfs(TreeNode node) {
21+
if (node == null) {
22+
return 1; // This node is covered
23+
}
24+
25+
int left = Dfs(node.left);
26+
int right = Dfs(node.right);
27+
28+
if (left == 0 || right == 0) {
29+
cameras++;
30+
return 2; // Placing a camera at this node
31+
}
32+
33+
return (left == 2 || right == 2) ? 1 : 0;
34+
// 2 indicates child has a camera, 1 means this node is covered
35+
// 0 indicates this node needs a camera
36+
}
37+
}
38+
39+
public class TreeNode {
40+
public int val;
41+
public TreeNode left;
42+
public TreeNode right;
43+
public TreeNode(int x) { val = x; }
44+
}
45+
```
46+
47+
## Approach 2: Dynamic Programming with State Tracking
48+
49+
### Solution
50+
csharp
51+
```csharp
52+
// Time Complexity: O(n)
53+
// Space Complexity: O(n)
54+
using System.Collections.Generic;
55+
56+
public class Solution {
57+
private const int HAS_CAMERA = 0;
58+
private const int COVERED = 1;
59+
private const int NEEDS_CAMERA = 2;
60+
61+
public int MinCameraCover(TreeNode root) {
62+
var dp = new Dictionary<TreeNode, int[]>();
63+
64+
return Dfs(root, dp) == NEEDS_CAMERA ? dp[root][HAS_CAMERA] + 1 : dp[root][HAS_CAMERA];
65+
}
66+
67+
private int Dfs(TreeNode node, Dictionary<TreeNode, int[]> dp) {
68+
if (node == null) {
69+
return COVERED;
70+
}
71+
72+
if (!dp.ContainsKey(node)) {
73+
var state = new int[3];
74+
75+
int left = Dfs(node.left, dp);
76+
int right = Dfs(node.right, dp);
77+
78+
if (left == NEEDS_CAMERA || right == NEEDS_CAMERA) {
79+
state[HAS_CAMERA] = dp.GetValueOrDefault(node, new int[]{0, 0, 0})[HAS_CAMERA] + 1;
80+
dp[node] = state;
81+
return HAS_CAMERA;
82+
}
83+
84+
if (left == HAS_CAMERA || right == HAS_CAMERA) {
85+
state[COVERED] = dp.GetValueOrDefault(node, new int[]{0, 0, 0})[COVERED];
86+
dp[node] = state;
87+
return COVERED;
88+
}
89+
90+
state[NEEDS_CAMERA] = dp.GetValueOrDefault(node, new int[]{0, 0, 0})[NEEDS_CAMERA];
91+
dp[node] = state;
92+
return NEEDS_CAMERA;
93+
}
94+
95+
return dp[node][0];
96+
}
97+
}
98+
99+
public class TreeNode {
100+
public int val;
101+
public TreeNode left;
102+
public TreeNode right;
103+
public TreeNode(int x) { val = x; }
104+
}
105+
```
106+
107+
Note: The second approach is a detailed version using dynamic programming concepts, but the greedy recursive version is typically more straightforward and efficient due to its optimizations for this specific problem.
2108

Lines changed: 105 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,106 @@
1-
# binary_tree_level_order_traversal.md
1+
# 102. [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
2+
3+
## Approach 1: Breadth-First Search (Using Queue)
4+
5+
### Solution
6+
csharp
7+
```csharp
8+
// Time Complexity: O(n), where n is the number of nodes in the tree
9+
// Space Complexity: O(n) for the queue and result storage
10+
11+
using System;
12+
using System.Collections.Generic;
13+
14+
public class Solution {
15+
public IList<IList<int>> LevelOrder(TreeNode root) {
16+
IList<IList<int>> result = new List<IList<int>>();
17+
if (root == null) {
18+
return result; // Return empty result if the tree is empty
19+
}
20+
21+
Queue<TreeNode> queue = new Queue<TreeNode>();
22+
queue.Enqueue(root);
23+
24+
while (queue.Count > 0) {
25+
int levelSize = queue.Count;
26+
List<int> currentLevel = new List<int>();
27+
28+
for (int i = 0; i < levelSize; i++) {
29+
TreeNode currentNode = queue.Dequeue(); // Process the current node
30+
currentLevel.Add(currentNode.val);
31+
32+
if (currentNode.left != null) {
33+
queue.Enqueue(currentNode.left); // Add left child to the queue
34+
}
35+
if (currentNode.right != null) {
36+
queue.Enqueue(currentNode.right); // Add right child to the queue
37+
}
38+
}
39+
40+
result.Add(currentLevel); // Add the current level to the result
41+
}
42+
43+
return result;
44+
}
45+
}
46+
47+
public class TreeNode {
48+
public int val;
49+
public TreeNode left;
50+
public TreeNode right;
51+
52+
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
53+
this.val = val;
54+
this.left = left;
55+
this.right = right;
56+
}
57+
}
58+
```
59+
60+
## Approach 2: Depth-First Search (Recursive)
61+
62+
### Solution
63+
csharp
64+
```csharp
65+
// Time Complexity: O(n), where n is the number of nodes in the tree
66+
// Space Complexity: O(h), where h is the height of the tree for recursion stack
67+
68+
using System;
69+
using System.Collections.Generic;
70+
71+
public class Solution {
72+
public IList<IList<int>> LevelOrder(TreeNode root) {
73+
IList<IList<int>> result = new List<IList<int>>();
74+
Dfs(root, 0, result);
75+
return result;
76+
}
77+
78+
private void Dfs(TreeNode node, int level, IList<IList<int>> result) {
79+
if (node == null) {
80+
return; // Base case: if the node is null, return
81+
}
82+
83+
if (level == result.Count) {
84+
result.Add(new List<int>()); // Create a new level in the result
85+
}
86+
87+
result[level].Add(node.val); // Add the current node's value to the current level
88+
89+
Dfs(node.left, level + 1, result); // Recurse for the left child
90+
Dfs(node.right, level + 1, result); // Recurse for the right child
91+
}
92+
}
93+
94+
public class TreeNode {
95+
public int val;
96+
public TreeNode left;
97+
public TreeNode right;
98+
99+
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
100+
this.val = val;
101+
this.left = left;
102+
this.right = right;
103+
}
104+
}
105+
```
2106

0 commit comments

Comments
 (0)