树:
递归(110):110. Balanced Binary Tree https://leetcode.com/problems/balanced-binary-tree/description/
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
if(Math.abs(depth(root.left)-depth(root.right))>1) return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
public static int depth(TreeNode root){
if(root==null) return 0;
return Math.max(depth(root.left),depth(root.right))+1;
}
层次遍历(513):513. Find Bottom Left Tree Value https://leetcode.com/problems/find-bottom-left-tree-value/description/
class Solution {
int maxDepth = -1;
int value = 0;
public int findBottomLeftValue(TreeNode root) {
inOrder(root, 0);
return value;
}
public void inOrder(TreeNode root, int depth){
if(root==null){
return;
}
if(maxDepth<depth){
maxDepth = depth;
value = root.val;
}
inOrder(root.left, depth+1);
inOrder(root.right, depth+1);
}
}
前中后序遍历(144):https://leetcode.com/problems/binary-tree-preorder-traversal/description/
List<Integer> result = new ArrayList<Integer>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root==null) return result;
if(root!=null) result.add(root.val);
if(root.left!=null) preorderTraversal(root.left);
if(root.right!=null) preorderTraversal(root.right);
return result;
}
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) return list;
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (!stack.empty() || node != null){
if(node != null){
stack.push(node);
list.add(node.val);
node = node.left;
} else {
node = stack.pop();
node = node.right;
}
}
return list;
}
BST(230):https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
public int kthSmallest(TreeNode root, int k) {
Stack s = new Stack<>();
while (root != null || !s.empty()){
while (root != null){
s.add(root);
root = root.left; }
root = (TreeNode)s.pop();
if (--k == 0) break;
root = root.right;
}
return root.val;
}
int n = 0;
public int kthSmallest(TreeNode root, int k) {
return dfs(root, k).val;
}
private TreeNode dfs(TreeNode root, int k) {
if(root == null) {
return null;
}
TreeNode node = dfs(root.left, k);
if(node != null) return node;
n++;
if(n == k) {
return root;
}
return dfs(root.right, k);
}
Trie(208):https://leetcode.com/problems/implement-trie-prefix-tree/description/
图:
二分图(785):785. Is Graph Bipartite? https://leetcode.com/problems/is-graph-bipartite/description/
public boolean isBipartite(int[][] graph) {
int r = graph.length;
int [] color = new int[r];
color[0]=1;
for(int i=0;i<graph.length;i++){
for(int j=0;j<graph[i].length;j++){
if(color[graph[i][j]]==0) color[graph[i][j]]= ~color[i];
else if(color[graph[i][j]]==color[i]) return false;
}
}
return true;
}
class Solution {
private enum Color {
NONE, BLUE, WHITE;
}
public boolean isBipartite(int[][] graph) {
Map<Integer, Color> map = new HashMap<>();
for (int i = 0; i < graph.length; ++i) map.put(i, Color.NONE);
for (int i = 0; i < graph.length; ++i) {
if (map.get(i) == Color.NONE) {
if(!dfs(i, graph, map, Color.BLUE)) return false;
}
}
return true;
}
private boolean dfs(int root, int[][] graph, Map<Integer, Color> visited, Color desiredColor) {
if (visited.get(root) != Color.NONE) return visited.get(root) == desiredColor;
visited.put(root, desiredColor);
boolean bipartite = true;
for (int edge : graph[root]) {
bipartite &= dfs(edge, graph, visited, desiredColor == Color.BLUE ? Color.WHITE : Color.BLUE);
}
return bipartite;
}
}
//更通用的版本
拓扑排序(207):207. Course Schedule https://leetcode.com/problems/course-schedule/description/
public boolean canFinish(int numCourses, int[][] prerequisites) {//找环,若存在,则条件不满足,Kahn's Algorithm
int[] reqCnt = new int[numCourses];
Stack<Integer> st = new Stack<>();
int totalCount = 0;
for(int i = 0; i < prerequisites.length; i++){
reqCnt[prerequisites[i][0]]++;
}
for(int i = 0; i < numCourses; i++){
if(reqCnt[i] == 0){
st.push(i);
totalCount++;
}
}//st存储的是入度为0的点
if(st.isEmpty())
return false;
while(!st.isEmpty()){
int val = st.pop();
for(int i = 0; i < prerequisites.length; i++){
if(prerequisites[i][1] == val){
reqCnt[prerequisites[i][0]]--;
if(reqCnt[prerequisites[i][0]] == 0){
st.push(prerequisites[i][0]);
totalCount++;
}
}
}
}
if(totalCount == numCourses)
return true;
return false;
}
并查集(684):684. Redundant Connection https://leetcode.com/problems/redundant-connection/description/
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int[] father = new int[1001];
for (int i = 1; i <= 1000; i++) {
father[i] = i;
}
for (int i = 0; i < edges.length; i++) {
int rootA = findFather(father, edges[i][0]);
int rootB = findFather(father, edges[i][1]);
if (rootA == rootB) return edges[i];
father[rootA] = rootB;
}
return new int[2];
}
public int findFather(int[] father, int x) {
if (x == father[x]) return x;
return father[x] = findFather(father, father[x]);
}
}
搜索:
BFS(279):https://leetcode.com/problems/perfect-squares/description/
public int numSquares(int n) {
int[] ret = new int[n + 1];
Arrays.fill(ret, Integer.MAX_VALUE);
ret[0] = 0;
ret[1] = 1;
for(int i = 1; i <= n; i++){
for(int j = 1; j * j <= i; j++){
ret[i] = Math.min(ret[i - j * j] + 1, ret[i]);
}
}
return ret[n];
}
DFS(695):https://leetcode.com/problems/max-area-of-island/description/
class Solution { //size函数能够传递地址
public static int maxAreaOfIsland(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0)
return 0;
int size[] = {0};
int maxSize = 0;
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
size[0] = 0;
dfs(grid, m, n, i, j, size);
maxSize = Math.max(maxSize, size[0]);
}
}
}
return maxSize;
}
private static void dfs(int[][] grid, int m, int n, int i, int j, int[] size) {
if (!isSafe(grid, m, n, i, j))
return ;
grid[i][j] = 0;
size[0]++;
dfs(grid, m, n, i + 1, j, size);
dfs(grid, m, n, i - 1, j, size);
dfs(grid, m, n, i, j + 1, size);
dfs(grid, m, n, i, j - 1, size);
}
private static boolean isSafe(int[][] grid, int m, int n, int r, int c) {
if (r >= 0 && c >= 0 && r < m && c < n && grid[r][c] == 1)
return true;
return false;
}
}
Backtracking(17):17. Letter Combinations of a Phone Number https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
letterCombinations(digits, "", list, map);
return list;
}
private void letterCombinations(String digits, String prefix, List<String> list, String[] map) {
if (digits.length() == prefix.length()) {
if (prefix.length() > 0)
list.add(prefix);
return;
}
int digit = digits.charAt(prefix.length()) - '0';
for(char c : map[digit].toCharArray()) {
letterCombinations(digits, prefix + c, list, map);
}
}
}
动态规划:
斐波那契数列(70):70. Climbing Stairs https://leetcode.com/problems/climbing-stairs/description/
public int climbStairs(int n) {
if(n==0||n==1) return 1;
if(n==2) return 2;
int p = 1, t = 1;
for(;n>0;n--){
t += p;
p = t - p;
}
return p;
}
矩阵路径(64):64. Minimum Path Sum https://leetcode.com/problems/minimum-path-sum/description/
public int minPathSum(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int[][] dp = new int[rows][cols];
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(i == 0 && j == 0){
dp[i][j] = grid[i][j];
}
else if(i == 0){
dp[i][j] = grid[i][j] + dp[i][j-1];
}
else if(j == 0){
dp[i][j] = grid[i][j] + dp[i-1][j];
}
else{
dp[i][j] = grid[i][j] + Math.min(dp[i][j-1],dp[i-1][j]);
}
}
}
return dp[rows-1][cols-1];
}
数组区间(303):303. Range Sum Query - Immutable https://leetcode.com/problems/range-sum-query-immutable/description/
class NumArray {
int[] sum;
public NumArray(int[] nums) {
sum = new int[nums.length+1];
sum[0] = 0;
for(int i = 0; i < nums.length; i++){
sum[i+1] = sum[i] + nums[i];
}
}
public int sumRange(int i, int j) {
return sum[j+1] - sum[i];
}
}
分割整数(343):343. Integer Break https://leetcode.com/problems/integer-break/description/
public int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
int three = n / 3;
int two = 0;
if((n - 3*three)==1) {two = 2; three -=1;}
else two = (n - 3*three) / 2;
return (int)(Math.pow(3,three) * Math.pow(2,two));
}
最长递增子序列(300):300. Longest Increasing Subsequence https://leetcode.com/problems/longest-increasing-subsequence/description/ eg [10,9,2,5,3,7,101,18]
----> 4
public int lengthOfLIS(int[] nums) {
if(nums==null) return 0;
if(nums.length<=1) return nums.length;
int [] top = new int[nums.length];
int size = 0;
for(int i=0;i<nums.length;i++){
int idx = binarySearch(top, nums[i], size);
top[idx] = nums[i];
if(idx==size) size++;
}
return size;
}
private int binarySearch(int[] nums, int val, int end){
int left = 0, right = end;
if(nums[left]>=val) return left;
while(left+1<right){
int mid = left + (right - left)/2;
if(nums[mid]>=val) right = mid;
else left = mid;
}
return right;
}
0-1 背包(416):416. Partition Equal Subset Sum https://leetcode.com/problems/partition-equal-subset-sum/description/ eg【1,2,3,4】
public boolean canPartition(int[] nums) {
int sum = 0;
for(int num : nums) sum += num;
if(sum % 2 != 0) return false;
sum /= 2;
//dp[i] is whether can get result i
boolean[] dp = new boolean[sum+1];
dp[0] = true;
for(int num : nums){//use number num
for(int i=sum; i>=0; i--){
// still remain i to get?
if(i>=num){//dp[num] 为 true
dp[i] = dp[i] || dp[i-num];
}
}
}
return dp[sum];
}
股票交易(309):https://leetcode.com/probl9ems/best-time-to-buy-and-sell-stock-with-cooldown/description/
字符串编辑(583):https://leetcode.com/problems/delete-operation-for-two-strings/description/