Skip to content

Commit 92240e3

Browse files
author
Botao Xiao
committed
[Function add]:1. Add leetcode solutions
1 parent fda60b5 commit 92240e3

39 files changed

+334
-2
lines changed

leetcode/174. Dungeon Game.md

100644100755
File mode changed.

leetcode/377. Combination Sum IV.md

100644100755
File mode changed.

leetcode/416. Partition Equal Subset Sum.md

100644100755
File mode changed.

leetcode/546. Remove Boxes.md

100644100755
File mode changed.

leetcode/547. Friend Circles.md

100644100755
File mode changed.

leetcode/576. Out of Boundary Paths.md

100644100755
File mode changed.

leetcode/583. Delete Operation for Two Strings.md

100644100755
File mode changed.

leetcode/664. Strange Printer.md

100644100755
File mode changed.

leetcode/673. Number of Longest Increasing Subsequence.md

100644100755
File mode changed.

leetcode/684. Redundant Connection.md

100644100755
+26-2
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,31 @@ Note:
6969
}
7070
```
7171

72-
* Method 2: Union find set to be added
72+
* Method 2: Union find set
73+
```Java
74+
class Solution {
75+
private int[] uf;
76+
public int[] findRedundantConnection(int[][] edges) {
77+
uf = new int[edges.length * 2 + 1];
78+
for(int i = 1; i < uf.length; i++){
79+
uf[i] = i;
80+
}
81+
for(int[] edge : edges){
82+
int p = find(edge[0]);
83+
int q = find(edge[1]);
84+
if(p == q) return edge;
85+
uf[p] = q;
86+
}
87+
return null;
88+
}
89+
private int find(int i){
90+
if(i != uf[i]){
91+
uf[i] = find(uf[i]);
92+
}
93+
return uf[i];
94+
}
95+
}
96+
```
7397

7498
### Reference
75-
1. [花花酱 LeetCode 684. Redundant Connection](http://zxi.mytechroad.com/blog/tree/leetcode-684-redundant-connection/)
99+
1. [花花酱 LeetCode 684. Redundant Connection](http://zxi.mytechroad.com/blog/tree/leetcode-684-redundant-connection/)

leetcode/685. Redundant Connection II.md

100644100755
File mode changed.

leetcode/688. Knight Probability in Chessboard.md

100644100755
File mode changed.

leetcode/712. Minimum ASCII Delete Sum for Two Strings.md

100644100755
File mode changed.

leetcode/721. Accounts Merge.md

100644100755
File mode changed.

leetcode/733. Flood Fill.md

100644100755
File mode changed.

leetcode/740. Delete and Earn.md

100644100755
File mode changed.

leetcode/741. Cherry Pickup.md

100644100755
File mode changed.

leetcode/743. Network Delay Time.md

100644100755
+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
## 743. Network Delay Time
2+
3+
### Question
4+
There are N network nodes, labelled 1 to N.
5+
6+
Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.
7+
8+
Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.
9+
10+
Note:
11+
1. N will be in the range [1, 100].
12+
2. K will be in the range [1, N].
13+
3. The length of times will be in the range [1, 6000].
14+
4. All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 0 <= w <= 100.
15+
16+
17+
### Solution:
18+
* Method 1: Floyd O(n ^ 3)
19+
```Java
20+
class Solution {
21+
public int networkDelayTime(int[][] times, int N, int K) {
22+
int[][] cost = new int[N + 1][N + 1];
23+
for(int[] c : cost) Arrays.fill(c, Integer.MAX_VALUE >> 1);
24+
for(int i = 1; i <= N; i++) cost[i][i] = 0;
25+
for(int[] time : times){
26+
cost[time[0]][time[1]] = time[2];
27+
}
28+
for(int k = 1; k <= N; k++){
29+
for(int i = 1; i <= N; i++){
30+
for(int j = 1; j <= N; j++){
31+
cost[i][j] = Math.min(cost[i][j], cost[i][k] + cost[k][j]);
32+
}
33+
}
34+
}
35+
int res = 0;
36+
for(int i = 1; i <= N; i++){
37+
if(cost[K][i] > 6000) return -1;
38+
res = Math.max(res, cost[K][i]);
39+
}
40+
return res;
41+
}
42+
}
43+
```
44+
45+
* Method 2: Dijkstra
46+
```Java
47+
class Solution {
48+
public int networkDelayTime(int[][] times, int N, int K) {
49+
int[][] cost = new int[N + 1][N + 1];
50+
for(int[] c : cost) Arrays.fill(c, Integer.MAX_VALUE >> 1);
51+
for(int i = 1; i <= N; i++) cost[i][i] = 0;
52+
for(int[] time : times){
53+
cost[time[0]][time[1]] = time[2];
54+
}
55+
int[] result = Arrays.copyOf(cost[K], N + 1);
56+
Set<Integer> set = new HashSet<>();
57+
set.add(K);
58+
while(set.size() < N){
59+
int index = -1, min = Integer.MAX_VALUE;
60+
for(int i = 1; i <= N; i++){
61+
if(!set.contains(i) && min > result[i]){
62+
index = i;
63+
min = result[i];
64+
}
65+
}
66+
for(int i = 0; i <= N; i++){
67+
if(index != -1 && !set.contains(i)){
68+
result[i] = Math.min(result[i], min + cost[index][i]);
69+
}
70+
}
71+
if(index == -1) return -1;
72+
else set.add(index);
73+
}
74+
int res = 0;
75+
for(int i = 1; i <= N; i++){
76+
if(result[i] > 6000) return -1;
77+
res = Math.max(result[i], res);
78+
}
79+
return res;
80+
}
81+
}
82+
```

leetcode/746. Min Cost Climbing Stairs.md

100644100755
File mode changed.

leetcode/785. Is Graph Bipartite.md

100644100755
File mode changed.

leetcode/787. Cheapest Flights Within K Stops.md

100644100755
File mode changed.

leetcode/790. Domino and Tromino Tiling.md

100644100755
File mode changed.

leetcode/801. Minimum Swaps To Make Sequences Increasing.md

100644100755
File mode changed.

leetcode/802. Find Eventual Safe States.md

100644100755
File mode changed.

leetcode/813. Largest Sum of Averages.md

100644100755
File mode changed.

leetcode/815. Bus Routes.md

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
## 815. Bus Routes
2+
3+
### Question
4+
We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.
5+
6+
We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.
7+
8+
```
9+
Example:
10+
Input:
11+
routes = [[1, 2, 7], [3, 6, 7]]
12+
S = 1
13+
T = 6
14+
Output: 2
15+
Explanation:
16+
The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
17+
```
18+
19+
Note:
20+
1. 1 <= routes.length <= 500.
21+
2. 1 <= routes[i].length <= 500.
22+
3. 0 <= routes[i][j] < 10 ^ 6.
23+
24+
### Solution
25+
* Method 1: bfs
26+
* we need to construct a graph using map, where key is the stop number and value is a list recording all buses passes through this stop.
27+
* we also need a boolean array to record which bus is visited since all stops on this routes can be visited.
28+
```Java
29+
class Solution {
30+
public int numBusesToDestination(int[][] routes, int S, int T) {
31+
if(S == T) return 0;
32+
// Create the graph
33+
Map<Integer, List<Integer>> g = new HashMap<>();
34+
for(int i = 0; i < routes.length; i++){
35+
for(int j = 0; j < routes[i].length; j++){
36+
List<Integer> buses = g.containsKey(routes[i][j]) ? g.get(routes[i][j]): new ArrayList<>();
37+
buses.add(i);
38+
g.put(routes[i][j], buses);
39+
}
40+
}
41+
Queue<Integer> q = new LinkedList<>();
42+
q.offer(S);
43+
int step = 0;
44+
boolean[] ride = new boolean[routes.length];
45+
while(!q.isEmpty()){
46+
int size = q.size();
47+
++step;
48+
for(int i = 0; i < size; i++){
49+
int cur = q.poll();
50+
// for each bus stop, get all buses that can pass through this stop
51+
List<Integer> buses = g.get(cur);
52+
for(Integer bus : buses){
53+
if(ride[bus]) continue;
54+
ride[bus] = true;
55+
// If never visited this bus before, add all stops of this bus to the queue.
56+
for(Integer stop : routes[bus]){
57+
if(stop == T) return step;
58+
q.offer(stop);
59+
}
60+
}
61+
}
62+
}
63+
return -1;
64+
}
65+
}
66+
```
67+
68+
### Reference
69+
1. [花花酱 LeetCode 815. Bus Routes](http://zxi.mytechroad.com/blog/graph/leetcode-815-bus-routes/)

leetcode/818. Race Car.md

100644100755
File mode changed.

leetcode/827. Making A Large Island.md

100644100755
File mode changed.

leetcode/839. Similar String Groups.md

100644100755
File mode changed.

leetcode/841. Keys and Rooms.md

100644100755
File mode changed.

leetcode/842. Split Array into Fibonacci Sequence.md

100644100755
File mode changed.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
## 847. Shortest Path Visiting All Nodes
2+
3+
### Question
4+
An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) is given as graph.
5+
6+
graph.length = N, and j != i is in the list graph[i] exactly once, if and only if nodes i and j are connected.
7+
8+
Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
9+
10+
```
11+
Example 1:
12+
13+
Input: [[1,2,3],[0],[0],[0]]
14+
Output: 4
15+
Explanation: One possible path is [1,0,2,0,3]
16+
Example 2:
17+
18+
Input: [[1],[0,2,4],[1,3,4],[2],[1,2]]
19+
Output: 4
20+
Explanation: One possible path is [0,1,4,2,3]
21+
```
22+
23+
Note:
24+
1. 1 <= graph.length <= 12(This means 2 ^ n level)
25+
2. 0 <= graph[i].length < graph.length
26+
27+
### Solution:
28+
* Method 1: bfs time complexity O(n * 2 ^ n)
29+
* Since we can visit a node multiple times, we need to have 2 variables to record breaking condition for a node:
30+
* cur_node
31+
* state: for current node, how many nodes were visited.
32+
* for a single node, if that state is visited means it is a duplicate condition and we can continue.
33+
```Java
34+
class Solution {
35+
public int shortestPathLength(int[][] graph) {
36+
int len = graph.length;
37+
int expect = (1 << len) - 1; //This set all bits to 1.
38+
Queue<int[]> q = new LinkedList<>(); // int[] saves current node, visited states
39+
for(int i = 0; i < len; i++)
40+
q.offer(new int[]{i, 1 << i}); // We could start from any points.
41+
// if for current node and state, we visit it again will be dulplicate, we can continue.
42+
boolean[][] visited = new boolean[len][1 << len];
43+
int step = -1;
44+
while(!q.isEmpty()){
45+
int size = q.size();
46+
++step;
47+
for(int i = 0; i < size; i++){
48+
int[] pair = q.poll();
49+
int node = pair[0];
50+
int state = pair[1];
51+
// We've visited all of the nodes
52+
if(state == expect) return step;
53+
if(visited[node][state]) continue;
54+
visited[node][state] = true;
55+
for(int next : graph[node]){
56+
q.offer(new int[]{next, state | (1 << next)});
57+
}
58+
}
59+
}
60+
return -1;
61+
}
62+
}
63+
```
64+
65+
### Reference
66+
1. [花花酱 LeetCode 847. Shortest Path Visiting All Nodes](http://zxi.mytechroad.com/blog/graph/leetcode-847-shortest-path-visiting-all-nodes/)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
## 864. Shortest Path to Get All Keys
2+
3+
### Question
4+
We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b", ...) are keys, and ("A", "B", ...) are locks.
5+
6+
We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions. We cannot walk outside the grid, or walk into a wall. If we walk over a key, we pick it up. We can't walk over a lock unless we have the corresponding key.
7+
8+
For some 1 <= K <= 6, there is exactly one lowercase and one uppercase letter of the first K letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.
9+
10+
Return the lowest number of moves to acquire all keys. If it's impossible, return -1.
11+
12+
```
13+
Example 1:
14+
15+
Input: ["@.a.#","###.#","b.A.B"]
16+
Output: 8
17+
Example 2:
18+
19+
Input: ["@..aA","..B#.","....b"]
20+
Output: 6
21+
```
22+
23+
Note:
24+
1. 1 <= grid.length <= 30
25+
2. 1 <= grid[0].length <= 30
26+
3. grid[i][j] contains only '.', '#', '@', 'a'-'f' and 'A'-'F'
27+
4. The number of keys is in [1, 6]. Each key has a different letter and opens exactly one lock.
28+
29+
### Solution:
30+
* Method 1: BFS
31+
* we use a integer to represent current state |bit 31:16 x index| bits 15:8 y index | bits 7-0 key|
32+
```Java
33+
class Solution {
34+
private static final int[][] dir = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
35+
public int shortestPathAllKeys(String[] grid) {
36+
int height = grid.length, width = grid[0].length();
37+
char[][] g = new char[height][width];
38+
int startX = -1, startY = -1;
39+
int expect = 0;
40+
for(int i = 0; i < height; i++){
41+
char[] arr = grid[i].toCharArray();
42+
for(int j = 0; j < width; j++){
43+
g[i][j] = arr[j];
44+
if(arr[j] == '@'){
45+
startX = i;
46+
startY = j;
47+
}else if(arr[j] >= 'a' && arr[j] <= 'f'){
48+
expect |= 1 << (arr[j] - 'a');
49+
}
50+
}
51+
}
52+
Queue<Integer> q = new LinkedList<>(); //int[] records [x, y]
53+
int startState = (startX << 16) | (startY << 8) | 0;
54+
q.offer(startState);
55+
int step = -1;
56+
Set<Integer> visited = new HashSet<>();
57+
while(!q.isEmpty()){
58+
int size = q.size();
59+
++step;
60+
for(int i = 0; i < size; i++){
61+
int cur = q.poll();
62+
if((cur & (0b111111)) == expect) return step;
63+
if(visited.contains(cur)) continue;
64+
visited.add(cur);
65+
int tx = 0, ty = 0;
66+
int curX = (cur >> 16) & 0xFF, curY = (cur >> 8) & 0xFF;
67+
int curKey = cur & 0xFF;
68+
for(int d = 0; d < 4; d++){
69+
tx = curX + dir[d][0];
70+
ty = curY + dir[d][1];
71+
if(tx >= 0 && tx < height && ty >= 0 && ty < width && g[tx][ty] != '#'){
72+
if(isUpper(g[tx][ty]) && (cur & (1 << (g[tx][ty] - 'A'))) == 0) continue;
73+
int nextState = (tx << 16) | (ty << 8) | (!isLower(g[tx][ty]) ? curKey : (curKey | (1 << (g[tx][ty] - 'A'))));
74+
q.offer(nextState);
75+
}
76+
}
77+
}
78+
}
79+
return -1;
80+
}
81+
private boolean isUpper(char c){
82+
return c >= 'A' && c <= 'F';
83+
}
84+
private boolean isLower(char c){
85+
return c >= 'a' && c <= 'f';
86+
}
87+
}
88+
```
89+
90+
### Reference
91+
1. [花花酱 LeetCode 864. Shortest Path to Get All Keys](https://zxi.mytechroad.com/blog/searching/leetcode-864-shortest-path-to-get-all-keys/)

leetcode/886. Possible Bipartition.md

100644100755
File mode changed.

leetcode/931. Minimum Falling Path Sum.md

100644100755
File mode changed.

leetcode/935. Knight Dialer.md

100644100755
File mode changed.

leetcode/952. Largest Component Size by Common Factor.md

100644100755
File mode changed.

leetcode/980. Unique Paths III.md

100644100755
File mode changed.

leetcode/990. Satisfiability of Equality Equations.md

100644100755
File mode changed.

0 commit comments

Comments
 (0)