Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
1. Fibonacci cut (stairs)
class Solution {
HashMap<Integer,Integer> cache = new HashMap<>();
public int fib(int N) {
if (cache.containsKey(N)) {
return cache.get(N);
}
int result;
if (N < 2) {
result = N;
}else {
result = fib(N-1) + fib(N-2);
}
cache.put(N,result);
return result;
}
}
2. merge two sorted linked list
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode pre = new ListNode(Integer.MIN_VALUE);
if (l1.val < l2.val) {
pre.next = l1;
l1.next = mergeTwoLists(l1.next,l2);
}else {
pre.next = l2;
l2.next = mergeTwoLists(l1,l2.next);
}
return pre.next;
}
}
3. Reverse list
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
return helper(cur,prev);
}
public ListNode helper(ListNode cur, ListNode prev) {
if (cur == null) return prev;
ListNode next = cur.next;
cur.next = prev;
return helper(next,cur);
}
}
4. The maximum depth of the binary tree
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
}
};