This note includes multiple leetcode algorithm problems with my solution
- 1. Letter Combinations of a Phone Number
- 2. Generate Parentheses
- 3. Combination Sum
- 4. Kth Smallest Element in a BST
- 5. Symmetric Tree
- 6. Binary Tree Level Order Traversal
- 7. Permutations
- 8. Search Insert Position
- 9. Path Sum III
- 10. Construct Binary Tree from Preorder and Inorder Traversal
- 11. Convert Sorted Array to Binary Search Tree
- 12. Course Schedule
- 13. Word Search
- 14. Search in Rotated Sorted Array
- 15. Invert Binary Tree
- 16. Flatten Binary Tree to Linked List
- 17. Intersection of Two Linked Lists
- 18. Reverse Linked List
- 19. Add Two Numbers
- 20. Rotting Oranges
- 21. Merge Two Sorted Lists
- 22. Copy List with Random Pointer
1. Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
1 | Input: digits = "23" |
Example 2:
1 | Input: digits = "" |
Example 3:
1 | Input: digits = "2" |
Constraints:
0 <= digits.length <= 4digits[i]is a digit in the range['2', '9'].
My Solution
1 | /** |
2. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
1 | Input: n = 3 |
Example 2:
1 | Input: n = 1 |
Constraints:
1 <= n <= 8
My Solution
1 | /** |
3. Combination Sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
1 | Input: candidates = [2,3,6,7], target = 7 |
Example 2:
1 | Input: candidates = [2,3,5], target = 8 |
Example 3:
1 | Input: candidates = [2], target = 1 |
Constraints:
1 <= candidates.length <= 302 <= candidates[i] <= 40- All elements of
candidatesare distinct. 1 <= target <= 40
My Solution
1 | /** |
优化空间:
可以先排序, 在
sum > target的时候就可以直接break, 可以更早终止无效分支。可以避免数组的不断复制(
[...currentResult, value])带来的额外空间开销。可以尝试用回溯的“回弹法”:
1
2
3 currentResult.push(value);
BackTracking(currentResult, sum + value, i);
currentResult.pop(); // 回弹
4. Kth Smallest Element in a BST
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Example 1:

1 | Input: root = [3,1,4,null,2], k = 1 |
Example 2:

1 | Input: root = [5,3,6,2,4,null,null,1], k = 3 |
Constraints:
- The number of nodes in the tree is
n. 1 <= k <= n <= 1040 <= Node.val <= 104
Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
My Solution
1 | /** |
5. Symmetric Tree
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:

1 | Input: root = [1,2,2,3,4,4,3] |
Example 2:

1 | Input: root = [1,2,2,null,3,null,3] |
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]. -100 <= Node.val <= 100
My Solution
1 | /** |
6. Binary Tree Level Order Traversal
Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
Example 1:

1 | Input: root = [3,9,20,null,null,15,7] |
Example 2:
1 | Input: root = [1] |
Example 3:
1 | Input: root = [] |
Constraints:
- The number of nodes in the tree is in the range
[0, 2000]. -1000 <= Node.val <= 1000
My Solution
1 | /** |
7. Permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
1 | Input: nums = [1,2,3] |
Example 2:
1 | Input: nums = [0,1] |
Example 3:
1 | Input: nums = [1] |
Constraints:
1 <= nums.length <= 6-10 <= nums[i] <= 10- All the integers of
numsare unique.
My Solution
1 | /** |
Optimized Solution
1 | /** |
8. Search Insert Position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
1 | Input: nums = [1,3,5,6], target = 5 |
Example 2:
1 | Input: nums = [1,3,5,6], target = 2 |
Example 3:
1 | Input: nums = [1,3,5,6], target = 7 |
Constraints:
1 <= nums.length <= 104-104 <= nums[i] <= 104numscontains distinct values sorted in ascending order.-104 <= target <= 104
My Solution
1 | /** |
9. Path Sum III
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
Example 1:

1 | Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 |
Example 2:
1 | Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 |
Constraints:
- The number of nodes in the tree is in the range
[0, 1000]. -109 <= Node.val <= 109-1000 <= targetSum <= 1000
My Solution
1 | /** |
10. Construct Binary Tree from Preorder and Inorder Traversal
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
Example 1:

1 | Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] |
Example 2:
1 | Input: preorder = [-1], inorder = [-1] |
Constraints:
1 <= preorder.length <= 3000inorder.length == preorder.length-3000 <= preorder[i], inorder[i] <= 3000preorderandinorderconsist of unique values.- Each value of
inorderalso appears inpreorder. preorderis guaranteed to be the preorder traversal of the tree.inorderis guaranteed to be the inorder traversal of the tree.
My Solution
1 | /** |
11. Convert Sorted Array to Binary Search Tree
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
Example 1:

1 | Input: nums = [-10,-3,0,5,9] |
Example 2:

1 | Input: nums = [1,3] |
Constraints:
1 <= nums.length <= 104-104 <= nums[i] <= 104numsis sorted in a strictly increasing order.
My Solution
1 | /** |
12. Course Schedule
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
- For example, the pair
[0, 1], indicates that to take course0you have to first take course1.
Return true if you can finish all courses. Otherwise, return false.
Example 1:
1 | Input: numCourses = 2, prerequisites = [[1,0]] |
Example 2:
1 | Input: numCourses = 2, prerequisites = [[1,0],[0,1]] |
Constraints:
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCourses- All the pairs prerequisites[i] are unique.
My Solution
1 | /** |
13. Word Search
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:

1 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" |
Example 2:

1 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" |
Example 3:

1 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" |
Constraints:
m == board.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15boardandwordconsists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board?
My Solution
1 | /** |
14. Search in Rotated Sorted Array
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
1 | Input: nums = [4,5,6,7,0,1,2], target = 0 |
Example 2:
1 | Input: nums = [4,5,6,7,0,1,2], target = 3 |
Example 3:
1 | Input: nums = [1], target = 0 |
Constraints:
1 <= nums.length <= 5000-104 <= nums[i] <= 104- All values of
numsare unique. numsis an ascending array that is possibly rotated.-104 <= target <= 104
My Solution
这道题的核心思路在于, 符合题意条件下, 如果只有一个拐点, 那么在二分的时候, 左右两边一定可以确认有一边是有序数组. 则可以根据这一边的有序数组来进行搜索 (因为有序数组任意截取也将继续为有序数组), 如果目标值不在有序数组中, 则对包含拐点的另一边重复上面的判断
1 | /** |
15. Invert Binary Tree
Given the root of a binary tree, invert the tree, and return its root.
Example 1:

1 | Input: root = [4,2,7,1,3,6,9] |
Example 2:

1 | Input: root = [2,1,3] |
Example 3:
1 | Input: root = [] |
Constraints:
- The number of nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
My Solution
1 | /** |
16. Flatten Binary Tree to Linked List
Given the root of a binary tree, flatten the tree into a “linked list”:
- The “linked list” should use the same
TreeNodeclass where therightchild pointer points to the next node in the list and theleftchild pointer is alwaysnull. - The “linked list” should be in the same order as a pre-order traversal of the binary tree.
Example 1:

1 | Input: root = [1,2,5,3,4,null,6] |
Example 2:
1 | Input: root = [] |
Example 3:
1 | Input: root = [0] |
Constraints:
- The number of nodes in the tree is in the range
[0, 2000]. -100 <= Node.val <= 100
Follow up: Can you flatten the tree in-place (with O(1) extra space)?
My Solution
思路:
1 | 1 |
node = 1,有左子树2- 找到
2的最右节点是4 - 把
5接到4.right - 把
2挂到1.right 1.left = null
- 找到
此时:
1 | 1 |
- 接着
node = 2,重复一样操作..
代码实现
1 | /** |
17. Intersection of Two Linked Lists
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:

The test cases are generated such that there are no cycles anywhere in the entire linked structure.
Note that the linked lists must retain their original structure after the function returns.
Example 1:

1 | Input: listA = [4,1,8,4,5], listB = [5,6,1,8,4,5] |
Example 2:

1 | Input: listA = [1,9,1,2,4], listB = [3,2,4] |
Example 3:

1 | Input: listA = [2,6,4], listB = [1,5] |
Constraints:
- The number of nodes of
listAis in them. - The number of nodes of
listBis in then. 1 <= m, n <= 3 * 1041 <= Node.val <= 105
Follow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory?
My Solution
1 | /** |
18. Reverse Linked List
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:

1 | Input: head = [1,2,3,4,5] |
Example 2:

1 | Input: head = [1,2] |
Example 3:
1 | Input: head = [] |
Constraints:
- The number of nodes in the list is the range
[0, 5000]. -5000 <= Node.val <= 5000
My Solution
1 | /** |
19. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:

1 | Input: l1 = [2,4,3], l2 = [5,6,4] |
Example 2:
1 | Input: l1 = [0], l2 = [0] |
Example 3:
1 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] |
Constraints:
- The number of nodes in each linked list is in the range
[1, 100]. 0 <= Node.val <= 9- It is guaranteed that the list represents a number that does not have leading zeros.
My Solution
1 | /** |
20. Rotting Oranges
You are given an m x n grid where each cell can have one of three values:
0representing an empty cell,1representing a fresh orange, or2representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
Example 1:

1 | Input: grid = [[2,1,1],[1,1,0],[0,1,1]] |
Example 2:
1 | Input: grid = [[2,1,1],[0,1,1],[1,0,1]] |
Example 3:
1 | Input: grid = [[0,2]] |
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10grid[i][j]is0,1, or2.
My Solution
1 | /** |
21. Merge Two Sorted Lists
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:

1 | Input: list1 = [1,2,4], list2 = [1,3,4] |
Example 2:
1 | Input: list1 = [], list2 = [] |
Example 3:
1 | Input: list1 = [], list2 = [0] |
Constraints:
- The number of nodes in both lists is in the range
[0, 50]. -100 <= Node.val <= 100- Both
list1andlist2are sorted in non-decreasing order.
My Solution
1 | /** |
22. Copy List with Random Pointer
A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.
Return the head of the copied linked list.
The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representingNode.valrandom_index: the index of the node (range from0ton-1) that therandompointer points to, ornullif it does not point to any node.
Your code will only be given the head of the original linked list.
Example 1:

1 | Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] |
Example 2:

1 | Input: head = [[1,1],[2,1]] |
Example 3:

1 | Input: head = [[3,null],[3,0],[3,null]] |
Constraints:
0 <= n <= 1000-104 <= Node.val <= 104Node.randomisnullor is pointing to some node in the linked list.
My Solution
1 | /** |
- 本文作者: Depasinre
- 本文链接: https:/Depasinre.github.io/2025/05/14/LeetCode-Top-100-Liked-Study-1/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!