├── 算法精髓-CPP.pdf ├── .gitattributes ├── LeetCodet题解.pdf ├── leetCode ├── oj.xlsx ├── sorts.pdf ├── leetcode.docx ├── Leetcode │ ├── Next Permutation.txt │ ├── Search Insert Position.txt │ ├── Jump Game.txt │ ├── Jump Game II.txt │ ├── Length of Last Word.txt │ ├── Unique Binary Search Trees.txt │ ├── Permutation Sequence.txt │ ├── Climbing Stairs.txt │ ├── Rotate Image.txt │ ├── Longest Common Prefix.txt │ ├── Count and Say.txt │ ├── Trapping Rain Water.txt │ ├── Plus One.txt │ ├── Remove Duplicates from Sorted Array.txt │ ├── Simplify Path .txt │ ├── Spiral Matrix II.txt │ ├── Valid Sudoku.txt │ ├── Unique Paths.txt │ ├── Same Tree.txt │ ├── N-Queens II.txt │ ├── Longest Valid Parentheses.txt │ ├── Combination Sum II.txt │ ├── Search in Rotated Sorted Array II.txt │ ├── Container With Most Water.txt │ ├── Merge Sorted Array.txt │ ├── Reverse Linked List II.txt │ ├── Remove Duplicates from Sorted Array II.txt │ ├── Maximum Subarray.txt │ ├── Pow(x, n).txt │ ├── Minimum Path Sum.txt │ ├── Permutations II.txt │ ├── Generate Parentheses.txt │ ├── Wildcard Matching.txt │ ├── Add Binary.txt │ ├── Minimum Depth of Binary Tree.txt │ ├── Valid Parentheses.txt │ ├── Unique Binary Search Trees II.txt │ ├── Convert Sorted Array to Binary Search Tree.txt │ ├── Distinct Subsequences.txt │ ├── Remove Duplicates from Sorted List.txt │ ├── Subsets.txt │ ├── Remove Duplicates from Sorted List II.txt │ ├── Search a 2D Matrix.txt │ ├── First Missing Positive.txt │ ├── Remove Element.txt │ ├── Search in Rotated Sorted Array.txt │ ├── Implement strStr().txt │ ├── Longest Substring Without Repeating Characters.txt │ ├── Divide Two Integers.txt │ ├── Maximal Rectangle .txt │ ├── Anagrams.txt │ ├── Sqrt(x).txt │ ├── Edit Distance.txt │ ├── Construct Binary Tree from Inorder and Postorder Traversal.txt │ ├── Construct Binary Tree from Preorder and Inorder Traversal.txt │ ├── Path Sum.txt │ ├── Remove Nth Node From End of List.txt │ ├── Median of Two Sorted Arrays.txt │ ├── Maximum Depth of Binary Tree.txt │ ├── Sudoku Solver.txt │ ├── Add Two Numbers.txt │ ├── Interleaving String.txt │ ├── 3Sum Closest.txt │ ├── Spiral Matrix.txt │ ├── Reverse Integer.txt │ ├── Longest Consecutive Sequence.txt │ ├── Combinations.txt │ ├── Valid Palindrome.txt │ ├── Binary Tree Maximum Path Sum.txt │ ├── Subsets II.txt │ ├── Substring with Concatenation of All Words.txt │ ├── Palindrome Partitioning.txt │ ├── Merge Two Sorted Lists.txt │ ├── Convert Sorted List to Binary Search Tree.txt │ ├── Binary Tree Inorder Traversal.txt │ ├── Multiply Strings.txt │ ├── Path Sum II.txt │ ├── Sum Root to Leaf Numbers.txt │ ├── Flatten Binary Tree to Linked List.txt │ ├── Regular Expression Matching.txt │ ├── Binary Tree Level Order Traversal.txt │ ├── Partition List.txt │ ├── Unique Paths II.txt │ ├── Word Search.txt │ ├── Merge Intervals.txt │ ├── Combination Sum.txt │ ├── Merge k Sorted Lists.txt │ ├── Insert Interval.txt │ ├── 3Sum.txt │ ├── Letter Combinations of a Phone Number.txt │ ├── Restore IP Addresses.txt │ ├── Recover Binary Search Tree.txt │ ├── Validate Binary Search Tree.txt │ ├── Follow up for problem Populating Next Right Pointers in Each Node..txt │ ├── Search for a Range.txt │ ├── Permutations.txt │ ├── Word Ladder.txt │ ├── Binary Tree Zigzag Level Order Traversal.txt │ ├── Swap Nodes in Pairs.txt │ ├── Populating Next Right Pointers in Each Node.txt │ ├── Decode Ways.txt │ ├── N-Queens.txt │ ├── Scramble String.txt │ ├── 4Sum.txt │ ├── Two Sum.txt │ ├── Surrounded Regions.txt │ ├── Set Matrix Zeroes.txt │ └── String to Integer (atoi).txt └── Version2.0 │ ├── Climbing Stairs.txt │ ├── Remove Element.txt │ ├── Sqrt(x).txt │ ├── Jump Game.txt │ ├── Maximum Depth of Binary Tree.txt │ ├── Container With Most Water.txt │ ├── Jump Game II.txt │ ├── Trapping Rain Water.txt │ ├── Pow(x, n).txt │ ├── Letter Combinations of a Phone Number.txt │ ├── N-Queens II.txt │ ├── Symmetric Tree.txt │ ├── Permutations.txt │ ├── Validate Binary Search Tree.txt │ ├── Search in Rotated Sorted Array.txt │ ├── Permutations II.txt │ ├── Combination Sum II.txt │ ├── Search in Rotated Sorted Array II.txt │ ├── Wildcard Matching.txt │ ├── Generate Parentheses.txt │ ├── Merge Two Sorted Lists.txt │ ├── Merge k Sorted Lists.txt │ ├── Binary Tree Level Order Traversal.txt │ ├── Swap Nodes in Pairs.txt │ └── Palindrome Number.txt ├── leetcode-cpp.pdf ├── lintcode-cpp.pdf └── leetcode-solution.pdf /算法精髓-CPP.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mr-Second/Leetcode/HEAD/算法精髓-CPP.pdf -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /LeetCodet题解.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mr-Second/Leetcode/HEAD/LeetCodet题解.pdf -------------------------------------------------------------------------------- /leetCode/oj.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mr-Second/Leetcode/HEAD/leetCode/oj.xlsx -------------------------------------------------------------------------------- /leetcode-cpp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mr-Second/Leetcode/HEAD/leetcode-cpp.pdf -------------------------------------------------------------------------------- /lintcode-cpp.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mr-Second/Leetcode/HEAD/lintcode-cpp.pdf -------------------------------------------------------------------------------- /leetCode/sorts.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mr-Second/Leetcode/HEAD/leetCode/sorts.pdf -------------------------------------------------------------------------------- /leetCode/leetcode.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mr-Second/Leetcode/HEAD/leetCode/leetcode.docx -------------------------------------------------------------------------------- /leetcode-solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mr-Second/Leetcode/HEAD/leetcode-solution.pdf -------------------------------------------------------------------------------- /leetCode/Leetcode/Next Permutation.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mr-Second/Leetcode/HEAD/leetCode/Leetcode/Next Permutation.txt -------------------------------------------------------------------------------- /leetCode/Leetcode/Search Insert Position.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mr-Second/Leetcode/HEAD/leetCode/Leetcode/Search Insert Position.txt -------------------------------------------------------------------------------- /leetCode/Version2.0/Climbing Stairs.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int climbStairs(int n) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if( n <= 2){ 6 | return n; 7 | } 8 | int first = 1; 9 | int second = 2; 10 | for(int i = 2; i < n ; i++){ 11 | int tmp = second; 12 | second += first; 13 | first = tmp; 14 | } 15 | return second; 16 | } 17 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Jump Game.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean canJump(int[] A) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if(A.length <= 1){ 6 | return true; 7 | } 8 | int max = A[0]; 9 | for(int i = 0; i < A.length && i <= max; i++){ 10 | if(A[i] + i > max){ 11 | max = A[i] + i; 12 | } 13 | } 14 | return max >= A.length -1?true:false; 15 | } 16 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Jump Game II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int jump(int[] A) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int step = 0; 6 | if(A.length <= 1){ 7 | return step; 8 | } 9 | int max = A[0]; 10 | int last = A[0]; 11 | for(int i = 0 ; i < A.length; i++){ 12 | if(i > last){ 13 | step++; 14 | last = max; 15 | } 16 | max = Math.max(max,A[i] + i); 17 | } 18 | return step + 1; 19 | } 20 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Length of Last Word.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLastWord(String s) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int last = 0; 6 | int cur = 0; 7 | for(int i = 0 ; i < s.length(); i++){ 8 | if(s.charAt(i) == ' '){ 9 | if(cur != 0){ 10 | last = cur; 11 | } 12 | cur = 0; 13 | }else{ 14 | cur++; 15 | } 16 | } 17 | return cur == 0 ? last:cur; 18 | } 19 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Unique Binary Search Trees.txt: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public int numTrees(int n) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if(n <= 2){ 7 | return n; 8 | } 9 | int[] res = new int[n + 1]; 10 | res[0] = res[1] = 1; 11 | res[2] = 2; 12 | for(int i = 3; i <= n; i++){ 13 | int tmp = 0; 14 | for(int j = 1; j <= i; j++){ 15 | tmp += res[j-1] * res[i-j]; 16 | } 17 | res[i] = tmp; 18 | } 19 | return res[n]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetCode/Leetcode/Permutation Sequence.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String getPermutation(int n, int k) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | List nums = new LinkedList(); 6 | int fac = 1; 7 | StringBuffer res = new StringBuffer(); 8 | for(int i = 0 ; i < n; i++){ 9 | nums.add(i + 1); 10 | fac *= (i + 1); 11 | } 12 | for(int i = n; i > 0; i--){ 13 | fac /= i; 14 | int cur = (k - 1) / fac; 15 | k -= cur * fac; 16 | res.append(nums.get(cur)); 17 | nums.remove(cur); 18 | } 19 | return res.toString(); 20 | } 21 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Climbing Stairs.txt: -------------------------------------------------------------------------------- 1 | You are climbing a stair case. It takes n steps to reach to the top. 2 | 3 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | 5 | =================================== 6 | 7 | Complexity: O(n) space O(n+1) 8 | 9 | Solution: 10 | 11 | public class Solution { 12 | public int climbStairs(int n) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | if(n <= 2){ 16 | return n; 17 | } 18 | int[] res = new int[n+1]; 19 | res[1] = 1; 20 | res[2] = 2; 21 | for(int i = 3 ; i <= n; i++){ 22 | res[i] = res[i-1] + res[i-2]; 23 | } 24 | return res[n]; 25 | } 26 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Rotate Image.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void rotate(int[][] matrix) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int n = matrix.length; 6 | for(int level = 0; level < n / 2; level++){ 7 | int nn = n -1; 8 | for(int len = 0 ; len < n - level * 2 -1; len++){ 9 | int x = level + len; 10 | int y = level; 11 | int tmp = matrix[x][y]; 12 | matrix[x][y] = matrix[nn - y][x]; 13 | matrix[nn -y][x] = matrix[nn -x][nn - y]; 14 | matrix[nn - x][nn - y] = matrix[y][nn - x]; 15 | matrix[y][nn - x] = tmp; 16 | } 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Longest Common Prefix.txt: -------------------------------------------------------------------------------- 1 | Write a function to find the longest common prefix string amongst an array of strings. 2 | 3 | ========================= 4 | 5 | public class Solution { 6 | public String longestCommonPrefix(String[] strs) { 7 | // Start typing your Java solution below 8 | // DO NOT write main() function 9 | if(strs == null || strs.length == 0){ 10 | return ""; 11 | } 12 | for(int i = 0 ; i < strs[0].length(); i++){ 13 | for(int j = 0; j < strs.length; j++){ 14 | if(strs[j].length() -1 < i || strs[j].charAt(i) != strs[0].charAt(i)){ 15 | return strs[0].substring(0,i); 16 | } 17 | } 18 | } 19 | return strs[0]; 20 | } 21 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Remove Element.txt: -------------------------------------------------------------------------------- 1 | Given an array and a value, remove all instances of that value in place and return the new length. 2 | 3 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 4 | 5 | 6 | ==================================== 7 | 8 | 9 | Solution: 10 | 11 | public class Solution { 12 | public int removeElement(int[] A, int elem) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | if(A.length == 0){ 16 | return 0; 17 | } 18 | int cur = 0; 19 | int next = 0; 20 | for(;next < A.length; next++){ 21 | if(A[next] != elem){ 22 | A[cur++] = A[next]; 23 | } 24 | } 25 | return cur; 26 | } 27 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Count and Say.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String countAndSay(int n) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | String res = "1"; 6 | for(int i = 2 ; i <= n; i++){ 7 | StringBuffer tres = new StringBuffer(); 8 | int times = 1; 9 | int j = 1; 10 | for(j = 1 ; j < res.length(); j++){ 11 | if( res.charAt(j) == res.charAt(j-1)){ 12 | times++; 13 | }else{ 14 | tres.append(times + "" + res.charAt(j-1)); 15 | times = 1; 16 | } 17 | } 18 | tres.append(times+ "" +res.charAt(j-1)); 19 | res = tres.toString(); 20 | tres = new StringBuffer(); 21 | } 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Trapping Rain Water.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int trap(int[] A) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int mid = 0; 6 | int res = 0; 7 | for(int i = 0 ; i < A.length; i++){ 8 | if(A[i] > A[mid]){ 9 | mid = i; 10 | } 11 | } 12 | int maxl = 0; 13 | for(int i = 1 ; i < mid; i++){ 14 | int high = Math.min(A[mid],A[maxl]); 15 | res += Math.max(0,high - A[i]); 16 | maxl = A[maxl] > A[i]?maxl:i; 17 | } 18 | int maxr = A.length -1; 19 | for(int i = A.length -2; i > mid; i--){ 20 | int high = Math.min(A[mid],A[maxr]); 21 | res += Math.max(0,high - A[i]); 22 | maxr = A[maxr] > A[i]?maxr:i; 23 | } 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Plus One.txt: -------------------------------------------------------------------------------- 1 | Given a number represented as an array of digits, plus one to the number. 2 | 3 | ======================================= 4 | 5 | Solution: 6 | 7 | public class Solution { 8 | public int[] plusOne(int[] digits) { 9 | // Start typing your Java solution below 10 | // DO NOT write main() function 11 | int add = 0; 12 | int n = digits.length; 13 | digits[n-1]++; 14 | for(int i = n-1 ; i >= 0; i--){ 15 | int tmp = digits[i] + add; 16 | add = tmp / 10; 17 | digits[i] = tmp % 10; 18 | } 19 | if( add == 0){ 20 | return digits; 21 | }else{ 22 | int[] res = new int[n+1]; 23 | res[0] = add; 24 | for(int i = 1 ; i < n+1; i++){ 25 | res[i] = digits[i-1]; 26 | } 27 | return res; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Sqrt(x).txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int sqrt(int x) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if( x <= 1){ 6 | return x; 7 | } 8 | int low = 1; 9 | int high = x ; 10 | while( low <= high){ 11 | int mid = low + (high - low) / 2; 12 | if( check(x,mid)){ 13 | return mid; 14 | }else if(x / mid > mid){ 15 | low = mid + 1; 16 | }else{ 17 | high = mid -1; 18 | } 19 | } 20 | return low; 21 | } 22 | 23 | boolean check(int x, int mid){ 24 | if( x / mid == mid){ 25 | return true; 26 | } 27 | if( x / mid > mid && x / (mid + 1) < (mid + 1)){ 28 | return true; 29 | } 30 | return false; 31 | } 32 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Remove Duplicates from Sorted Array.txt: -------------------------------------------------------------------------------- 1 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 2 | 3 | Do not allocate extra space for another array, you must do this in place with constant memory. 4 | 5 | For example, 6 | Given input array A = [1,1,2], 7 | 8 | Your function should return length = 2, and A is now [1,2]. 9 | 10 | ============================== 11 | 12 | Solution: 13 | 14 | public class Solution { 15 | public int removeDuplicates(int[] A) { 16 | // Start typing your Java solution below 17 | // DO NOT write main() function 18 | if(A.length <= 1){ 19 | return A.length; 20 | } 21 | int cur = 0; 22 | for(int i = 1; i < A.length; i++){ 23 | if(A[i] > A[cur]){ 24 | A[++cur] = A[i]; 25 | } 26 | } 27 | return cur + 1; 28 | } 29 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Simplify Path .txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String simplifyPath(String path) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | Stack sts = new Stack(); 6 | String[] its = path.split("/"); 7 | for(String it : its){ 8 | if(it.length() == 0){continue;} 9 | if(it.equals("..")){ 10 | if(!sts.empty()){ 11 | sts.pop(); 12 | } 13 | }else if(it.equals(".")){ 14 | continue; 15 | }else{ 16 | sts.push(it); 17 | } 18 | } 19 | StringBuffer res = new StringBuffer(); 20 | for(String st : sts){ 21 | res.append("/" + st); 22 | } 23 | if(res.length() == 0){ 24 | res.append("/"); 25 | } 26 | return res.toString(); 27 | } 28 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Spiral Matrix II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[][] generateMatrix(int n) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int[][] res = new int[n][n]; 6 | int cur = 1; 7 | for(int i = 0 ; i < n / 2; i++){ 8 | int len = n - i * 2 -1; 9 | //top 10 | for(int j = 0 ; j < len; j++){ 11 | res[i][i + j] = cur++; 12 | } 13 | for(int j = 0 ; j < len; j++){ 14 | res[i + j][i + len] = cur++; 15 | } 16 | for(int j = 0 ; j < len; j++){ 17 | res[i + len][i + len - j] = cur++; 18 | } 19 | for(int j = 0 ; j < len; j++){ 20 | res[i + len - j][i] = cur++; 21 | } 22 | } 23 | if( n % 2 != 0){ 24 | res[n/2][n/2] = cur; 25 | } 26 | return res; 27 | } 28 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Valid Sudoku.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isValidSudoku(char[][] board) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int n = board.length; 6 | boolean[][] rows = new boolean[n][n]; 7 | boolean[][] cols = new boolean[n][n]; 8 | boolean[][] block = new boolean[n][n]; 9 | for(int i = 0 ; i < n; i++){ 10 | for(int j = 0 ; j < n; j++){ 11 | if(board[i][j] == '.'){continue;} 12 | int num = board[i][j] - '0'; 13 | if(rows[i][num-1] == true || cols[j][num-1] == true || block[i - i % 3 + j / 3][num-1] == true){ 14 | return false; 15 | } 16 | rows[i][num-1] = true; 17 | cols[j][num-1] = true; 18 | block[i - i % 3 + j / 3][num-1] = true; 19 | } 20 | } 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Unique Paths.txt: -------------------------------------------------------------------------------- 1 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 2 | 3 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 4 | 5 | How many possible unique paths are there? 6 | 7 | ================================== 8 | 9 | Solution: 10 | 11 | public class Solution { 12 | public int uniquePaths(int m, int n) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | if(m == 0 || n == 0){ 16 | return 0; 17 | } 18 | int[] res = new int[n]; 19 | for(int i = 0 ; i < n ;i++){ 20 | res[i] = 1; 21 | } 22 | for(int i = 1; i < m ;i++){ 23 | for(int j = 1; j < n; j++){ 24 | res[j] = res[j] + res[j-1]; 25 | } 26 | } 27 | return res[n-1]; 28 | } 29 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Same Tree.txt: -------------------------------------------------------------------------------- 1 | Given two binary trees, write a function to check if they are equal or not. 2 | 3 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 4 | 5 | ==================== 6 | 7 | Solution: 8 | 9 | /** 10 | * Definition for binary tree 11 | * public class TreeNode { 12 | * int val; 13 | * TreeNode left; 14 | * TreeNode right; 15 | * TreeNode(int x) { val = x; } 16 | * } 17 | */ 18 | public class Solution { 19 | public boolean isSameTree(TreeNode p, TreeNode q) { 20 | // Start typing your Java solution below 21 | // DO NOT write main() function 22 | if(p == null){ 23 | return q == null; 24 | }else if(q == null){ 25 | return p == null; 26 | } 27 | if(p.val != q.val){ 28 | return false; 29 | }else{ 30 | return isSameTree(p.left,q.left) && isSameTree(p.right,q.right); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Jump Game.txt: -------------------------------------------------------------------------------- 1 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 2 | 3 | Each element in the array represents your maximum jump length at that position. 4 | 5 | Determine if you are able to reach the last index. 6 | 7 | For example: 8 | A = [2,3,1,1,4], return true. 9 | 10 | A = [3,2,1,0,4], return false. 11 | 12 | ==================================================== 13 | 14 | Solution: 15 | 16 | public class Solution { 17 | public boolean canJump(int[] A) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | if(A.length == 0){ 21 | return false; 22 | } 23 | int max = 0; 24 | for(int i = 0 ; i < A.length && i <= max; i++){ 25 | if(A[i] + i > max){ 26 | max = A[i] + i; 27 | } 28 | } 29 | if(max >= A.length -1){ 30 | return true; 31 | }else{ 32 | return false; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/N-Queens II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int totalNQueens(int n) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if(n <= 0){ 6 | return 0; 7 | } 8 | int[] queens = new int[n]; 9 | return dfs(queens,0); 10 | } 11 | 12 | int dfs(int[] queens, int index){ 13 | if(index == queens.length){ 14 | return 1; 15 | } 16 | int res = 0; 17 | for(int i = 0 ; i < queens.length; i++){ 18 | queens[index] = i; 19 | if(valid(queens,index)){ 20 | res += dfs(queens,index+1); 21 | } 22 | } 23 | return res; 24 | } 25 | 26 | boolean valid(int[] queens,int index){ 27 | for(int i = 0 ; i < index; i++){ 28 | if(queens[i] == queens[index] || Math.abs(i - index) == Math.abs(queens[i] - queens[index])){ 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Maximum Depth of Binary Tree.txt: -------------------------------------------------------------------------------- 1 | 2 | Given a binary tree, find its maximum depth. 3 | 4 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | 6 | ==================================================== 7 | 8 | 9 | Solution: 10 | 11 | /** 12 | * Definition for binary tree 13 | * public class TreeNode { 14 | * int val; 15 | * TreeNode left; 16 | * TreeNode right; 17 | * TreeNode(int x) { val = x; } 18 | * } 19 | */ 20 | public class Solution { 21 | public int maxDepth(TreeNode root) { 22 | // Start typing your Java solution below 23 | // DO NOT write main() function 24 | if(root == null){ 25 | return 0; 26 | } 27 | return max(root); 28 | } 29 | 30 | int max(TreeNode node){ 31 | if(node == null){ 32 | return 0; 33 | } 34 | int left = max(node.left); 35 | int right = max(node.right); 36 | return Math.max(left,right) + 1; 37 | } 38 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Longest Valid Parentheses.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestValidParentheses(String s) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if(s.length() <= 1){ 6 | return 0; 7 | } 8 | int res = 0; 9 | Stack pos = new Stack(); 10 | for(int i = 0 ; i < s.length(); i++){ 11 | if(s.charAt(i) == '('){ 12 | pos.push(i); 13 | }else{ 14 | if(pos.empty() || s.charAt(pos.peek()) != '('){ 15 | pos.push(i); 16 | }else{ 17 | int len = 0; 18 | pos.pop(); 19 | if(pos.empty()){ 20 | len = i+1; 21 | }else{ 22 | len = i - pos.peek(); 23 | } 24 | res = Math.max(res,len); 25 | } 26 | } 27 | } 28 | return res; 29 | } 30 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Combination Sum II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> combinationSum2(int[] num, int target) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | ArrayList> res = new ArrayList>(); 6 | Arrays.sort(num); 7 | ArrayList adds = new ArrayList(); 8 | dfs(num,target,0,adds,res); 9 | return res; 10 | } 11 | 12 | void dfs(int[] num,int target,int index,ArrayList adds,ArrayList> res){ 13 | if(target == 0){ 14 | res.add(new ArrayList(adds)); 15 | return ; 16 | }else if(target < 0){ 17 | return; 18 | } 19 | for(int i = index; i < num.length; i++){ 20 | if(i != index && num[i] == num[i - 1]){continue;} 21 | adds.add(num[i]); 22 | dfs(num,target - num[i],i+1,adds,res); 23 | adds.remove(adds.size() -1); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Search in Rotated Sorted Array II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean search(int[] A, int target) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if(A.length == 0){ 6 | return false; 7 | } 8 | int low = 0; 9 | int high = A.length -1; 10 | while(low <= high){ 11 | int mid = low + (high - low) / 2; 12 | if(A[mid] == target){ 13 | return true; 14 | } 15 | if(A[mid] > A[low]){ 16 | if(target >A[mid] || target < A[low]){ 17 | low = mid + 1; 18 | }else{ 19 | high = mid -1; 20 | } 21 | }else if(A[mid] < A[low]){ 22 | if(target > A[high] || target < A[mid]){ 23 | high = mid -1; 24 | }else{ 25 | low = mid + 1; 26 | } 27 | }else{ 28 | low++; 29 | } 30 | } 31 | return false; 32 | } 33 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Container With Most Water.txt: -------------------------------------------------------------------------------- 1 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 2 | 3 | Note: You may not slant the container. 4 | 5 | ===================== 6 | 7 | 8 | 9 | Solution: 10 | 11 | public class Solution { 12 | public int maxArea(int[] height) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | if(height == null || height.length < 2){ 16 | return 0; 17 | } 18 | int max = 0; 19 | int low = 0; 20 | int high = height.length -1; 21 | while(low < high){ 22 | max = Math.max(max,Math.min(height[low],height[high]) * (high - low)); 23 | if(height[low] > height[high]){ 24 | high--; 25 | }else{ 26 | low++; 27 | } 28 | } 29 | return max; 30 | } 31 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Merge Sorted Array.txt: -------------------------------------------------------------------------------- 1 | Given two sorted integer arrays A and B, merge B into A as one sorted array. 2 | 3 | Note: 4 | You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. 5 | 6 | ============================= 7 | 8 | Complexity time: O(m+n) 9 | 10 | take care the edge of A and B 11 | 12 | Solution: 13 | 14 | public class Solution { 15 | public void merge(int A[], int m, int B[], int n) { 16 | // Start typing your Java solution below 17 | // DO NOT write main() function 18 | if(n == 0){ 19 | return; 20 | } 21 | int index = m + n -1; 22 | while(n >= 1){ 23 | if(m == 0){ 24 | A[index--] = B[n-1]; 25 | n--; 26 | }else{ 27 | int max = Math.max(A[m-1],B[n-1]); 28 | A[index--] = max; 29 | if(max == A[m-1]){ 30 | m--; 31 | }else{ 32 | n--; 33 | } 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Reverse Linked List II.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode reverseBetween(ListNode head, int m, int n) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | if(m == n){ 17 | return head; 18 | } 19 | ListNode preM = null; 20 | ListNode dummy = new ListNode(0); 21 | ListNode pre = dummy; 22 | dummy.next = head; 23 | for(int i = 1; i <= n; i++){ 24 | if(i == m){ 25 | preM = pre; 26 | } 27 | if(i > m && i <= n){ 28 | pre.next = head.next; 29 | head.next = preM.next; 30 | preM.next = head; 31 | head = pre; 32 | } 33 | pre = head; 34 | head = head.next; 35 | } 36 | return dummy.next; 37 | } 38 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Remove Duplicates from Sorted Array II.txt: -------------------------------------------------------------------------------- 1 | Follow up for "Remove Duplicates": 2 | What if duplicates are allowed at most twice? 3 | 4 | For example, 5 | Given sorted array A = [1,1,1,2,2,3], 6 | 7 | Your function should return length = 5, and A is now [1,1,2,2,3]. 8 | 9 | ==================================== 10 | 11 | use a times variable to record how many times the same key appears 12 | 13 | 14 | Solution: 15 | 16 | public class Solution { 17 | public int removeDuplicates(int[] A) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | if(A.length <= 2){ 21 | return A.length; 22 | } 23 | int n = A.length; 24 | int times = 1; 25 | int cur = 0; 26 | for(int i = 1; i < n;i++){ 27 | if(A[i] == A[cur]){ 28 | if(times < 2){ 29 | A[++cur] = A[i]; 30 | times++; 31 | } 32 | }else{ 33 | A[++cur] = A[i]; 34 | times = 1; 35 | } 36 | } 37 | return cur + 1; 38 | } 39 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Maximum Subarray.txt: -------------------------------------------------------------------------------- 1 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 2 | 3 | For example, given the array [?2,1,?3,4,?1,2,1,?5,4], 4 | the contiguous subarray [4,?1,2,1] has the largest sum = 6. 5 | 6 | More practice: 7 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 8 | 9 | 10 | Complexity: time:O(n) space O(1) 11 | 12 | take care of the initial.. 13 | 14 | Solution: 15 | 16 | public class Solution { 17 | public int maxSubArray(int[] A) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | if(A.length == 0){ 21 | return 0; 22 | } 23 | int res = A[0]; 24 | int max = A[0]; 25 | for(int i = 1 ; i < A.length; i++){ 26 | if(max > 0 ){ 27 | max += A[i]; 28 | }else{ 29 | max = A[i]; 30 | } 31 | if(res < max){ 32 | res = max; 33 | } 34 | } 35 | return res; 36 | } 37 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Pow(x, n).txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public double pow(double x, int n) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if(x == 0){ 6 | return 0; 7 | } 8 | return itePow(x,n); 9 | } 10 | 11 | //recursive solution 12 | double recPow(double x, int n){ 13 | if(n == 0){ 14 | return 1; 15 | } 16 | double tmp = recPow(x,n / 2); 17 | if( n % 2 == 0){ 18 | return tmp * tmp; 19 | }else{ 20 | if(n > 0){ 21 | return tmp * tmp * x; 22 | }else{ 23 | return tmp * tmp / x; 24 | } 25 | } 26 | } 27 | 28 | //iterative solution 29 | double itePow(double x, int n){ 30 | long nn = n; 31 | double res = 1; 32 | if(n < 0 ){ 33 | nn *= -1; 34 | } 35 | while(nn > 0){ 36 | if((nn & 1) == 1){ 37 | res *= x; 38 | } 39 | x *= x; 40 | nn = nn >> 1; 41 | } 42 | return n < 0?1 / res:res; 43 | } 44 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Container With Most Water.txt: -------------------------------------------------------------------------------- 1 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 2 | 3 | Note: You may not slant the container. 4 | 5 | ===================== 6 | 7 | 8 | 9 | Solution: 10 | 11 | public class Solution { 12 | public int maxArea(int[] height) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | if(height.length <= 1){ 16 | return 0; 17 | } 18 | int low = 0; 19 | int high = height.length -1; 20 | int max = 0; 21 | while( low < high){ 22 | int size =( high - low ) * Math.min(height[low],height[high]); 23 | if(max < size){ 24 | max = size; 25 | } 26 | if(height[low] > height[high]){ 27 | high--; 28 | }else{ 29 | low ++; 30 | } 31 | } 32 | return max; 33 | } 34 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Minimum Path Sum.txt: -------------------------------------------------------------------------------- 1 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 2 | 3 | Note: You can only move either down or right at any point in time. 4 | 5 | ======================= 6 | 7 | use one array to record the results. 8 | 9 | Solution: 10 | 11 | public class Solution { 12 | public int minPathSum(int[][] grid) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | int n = grid.length; 16 | if(n == 0){ 17 | return 0; 18 | } 19 | int m = grid[0].length; 20 | int[] res = new int[m]; 21 | for(int i = 0 ; i < n; i++){ 22 | for(int j = 0 ; j < m; j++){ 23 | if(i == 0){ 24 | if(j != 0){res[j] += res[j -1];} 25 | res[j] += grid[i][j]; 26 | }else if(j == 0){ 27 | res[j] += grid[i][j]; 28 | }else{ 29 | res[j] = Math.min(res[j],res[j-1]) + grid[i][j]; 30 | } 31 | } 32 | } 33 | return res[m-1]; 34 | } 35 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Permutations II.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> permute(int[] num) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | ArrayList> res = new ArrayList>(); 6 | ArrayList adds = new ArrayList(); 7 | Arrays.sort(num); 8 | dfs(num,0,adds,res); 9 | return res; 10 | } 11 | 12 | void dfs(int[] num,int index,ArrayList adds,ArrayList> res){ 13 | if(index == num.length){ 14 | res.add(new ArrayList(adds)); 15 | return; 16 | } 17 | for(int i = index; i < num.length; i++){ 18 | if(i != index && num[i] == num[index]){continue;} 19 | swap(num,index,i); 20 | adds.add(num[index]); 21 | dfs(num,index+1,adds,res); 22 | adds.remove(adds.size() -1); 23 | swap(num,index,i); 24 | } 25 | } 26 | 27 | void swap(int[] num,int ia, int ib){ 28 | int tmp = num[ib]; 29 | num[ib] = num[ia]; 30 | num[ia] = tmp; 31 | } 32 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Generate Parentheses.txt: -------------------------------------------------------------------------------- 1 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 2 | 3 | For example, given n = 3, a solution set is: 4 | 5 | "((()))", "(()())", "(())()", "()(())", "()()()" 6 | 7 | ============================= 8 | 9 | Complexity 10 | 11 | DFS, but take care that repeated cases 12 | 13 | Solution: 14 | public class Solution { 15 | public ArrayList generateParenthesis(int n) { 16 | // Start typing your Java solution below 17 | // DO NOT write main() function 18 | ArrayList res = new ArrayList(); 19 | if(n == 0){ 20 | return res; 21 | } 22 | solve(n,0,0,"",res); 23 | return res; 24 | } 25 | 26 | void solve(int n,int left,int right,String cur, ArrayList res){ 27 | if(left == n){ 28 | for(int i = 0 ; i < n- right; i++){ 29 | cur += ')'; 30 | } 31 | res.add(cur); 32 | return; 33 | } 34 | solve(n,left+1,right,cur+'(',res); 35 | if(left > right){ 36 | solve(n,left,right+1,cur+')',res); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Wildcard Matching.txt: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public boolean isMatch(String s, String p) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | if(s == null){return p == null;} 7 | return match(s,p); 8 | } 9 | boolean match(String s, String p){ 10 | 11 | int is = 0 ; 12 | int ip = 0 ; 13 | int markp = -1; 14 | int marks = -1; 15 | while(is < s.length()){ 16 | if(ip != p.length() && p.charAt(ip) == '*'){ 17 | markp = ip; 18 | marks = is; 19 | ip++; 20 | }else{ 21 | if(ip != p.length() && (p.charAt(ip) == '?' || s.charAt(is) == p.charAt(ip))) 22 | { 23 | ip++;is++; 24 | }else if(markp >= 0){ 25 | ip = markp + 1; 26 | is = ++marks; 27 | }else{ 28 | return false; 29 | } 30 | } 31 | } 32 | while(ip < p.length() && p.charAt(ip) == '*'){ip++;} 33 | return is == s.length() && ip == p.length(); 34 | } 35 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Add Binary.txt: -------------------------------------------------------------------------------- 1 | Given two binary strings, return their sum (also a binary string). 2 | 3 | For example, 4 | a = "11" 5 | b = "1" 6 | Return "100". 7 | 8 | ============================================= 9 | 10 | Complexity : O(n + m) 11 | 12 | Solution: 13 | 14 | 15 | public class Solution { 16 | public String addBinary(String a, String b) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | if(a.length() == 0 || b.length() == 0){ 20 | return (a.length() == 0)? b:a; 21 | } 22 | int add = 0; 23 | StringBuffer res = new StringBuffer(); 24 | Stack sts = new Stack(); 25 | int ia = a.length() -1; 26 | int ib = b.length() -1; 27 | while(ia >= 0 || ib>= 0){ 28 | if(ia >= 0){ 29 | add += a.charAt(ia) - '0';ia--; 30 | } 31 | if(ib >= 0){add += b.charAt(ib) - '0'; ib--;} 32 | sts.push(add % 2); 33 | add = add / 2; 34 | } 35 | if(add == 1){sts.push(1);} 36 | while(!sts.empty()){ 37 | res.append("" + sts.pop()); 38 | } 39 | return res.toString(); 40 | } 41 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Jump Game II.txt: -------------------------------------------------------------------------------- 1 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 2 | 3 | Each element in the array represents your maximum jump length at that position. 4 | 5 | Your goal is to reach the last index in the minimum number of jumps. 6 | 7 | For example: 8 | Given array A = [2,3,1,1,4] 9 | 10 | The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) 11 | 12 | ============================== 13 | 14 | in the last max range, update current max. when i bigger than last max. step ++, and update last max = current max 15 | 16 | Solution: 17 | 18 | public class Solution { 19 | public int jump(int[] A) { 20 | // Start typing your Java solution below 21 | // DO NOT write main() function 22 | if(A.length <= 1){ 23 | return 0; 24 | } 25 | int max = 0; 26 | int res = 0; 27 | int cur = 0; 28 | for(int i = 0 ; i < A.length; i++){ 29 | if(i > cur){ 30 | res++; 31 | cur = max; 32 | } 33 | max = Math.max(max,A[i] + i); 34 | } 35 | return res; 36 | } 37 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Minimum Depth of Binary Tree.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, find its minimum depth. 2 | 3 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 4 | 5 | ============================= 6 | 7 | be careful of case that node only contains one children. 8 | 9 | 10 | Solution: 11 | 12 | /** 13 | * Definition for binary tree 14 | * public class TreeNode { 15 | * int val; 16 | * TreeNode left; 17 | * TreeNode right; 18 | * TreeNode(int x) { val = x; } 19 | * } 20 | */ 21 | public class Solution { 22 | public int minDepth(TreeNode root) { 23 | // Start typing your Java solution below 24 | // DO NOT write main() function 25 | if(root == null){ 26 | return 0; 27 | } 28 | return minPath(root); 29 | } 30 | 31 | int minPath(TreeNode node){ 32 | if(node == null){ 33 | return 0; 34 | } 35 | int left = minPath(node.left); 36 | int right = minPath(node.right); 37 | if(left == 0 || right == 0){ 38 | return (left == 0?right:left) + 1; 39 | }else{ 40 | return Math.min(left,right) + 1; 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Valid Parentheses.txt: -------------------------------------------------------------------------------- 1 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 2 | 3 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 4 | 5 | ========================================== 6 | 7 | Complexity : O(n) space O(n) 8 | 9 | Solution: 10 | 11 | public class Solution { 12 | public boolean isValid(String s) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | if(s == null || s.length() % 2 != 0){ 16 | return false; 17 | } 18 | Stack sts = new Stack(); 19 | for(int i = 0 ; i < s.length();i++){ 20 | if(s.charAt(i) == ')'){ 21 | if(sts.empty() || sts.pop() != '('){return false;} 22 | }else if(s.charAt(i) == ']'){ 23 | if(sts.empty() || sts.pop() != '['){return false;} 24 | }else if(s.charAt(i) == '}'){ 25 | if(sts.empty() || sts.pop() != '{'){return false;} 26 | }else{ 27 | sts.push(s.charAt(i)); 28 | } 29 | } 30 | if(sts.empty()){return true;} 31 | return false; 32 | } 33 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Trapping Rain Water.txt: -------------------------------------------------------------------------------- 1 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 2 | 3 | For example, 4 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 5 | 6 | ============================= 7 | 8 | for each column, the volumn which it can contain is Math.min(bigleft,bigright) - height 9 | 10 | Solution: 11 | 12 | public class Solution { 13 | public int trap(int[] A) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | if(A.length <= 2){ 17 | return 0; 18 | } 19 | int n = A.length; 20 | int[] max = new int[n]; 21 | for(int i = 1 ; i < n;i++){ 22 | if(A[i - 1] > max[i-1]){ 23 | max[i] = A[i - 1]; 24 | }else{ 25 | max[i] = max[i-1]; 26 | } 27 | } 28 | int res = 0; 29 | int height = A[n-1]; 30 | for(int i = n - 2; i >= 0 ; i--){ 31 | int len = Math.max(Math.min(max[i],height) - A[i],0); 32 | res += len; 33 | if(A[i] > height){ 34 | height = A[i]; 35 | } 36 | } 37 | return res; 38 | } 39 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Pow(x, n).txt: -------------------------------------------------------------------------------- 1 | Implement pow(x, n). 2 | 3 | 4 | =============================== 5 | 6 | recurrence and iterative methods 7 | 8 | public class Solution { 9 | public double pow(double x, int n) { 10 | // Start typing your Java solution below 11 | // DO NOT write main() function 12 | return powr(x,n); 13 | } 14 | 15 | ///recurrence 16 | double powr(double x, int n){ 17 | if(n == 0){ 18 | return 1; 19 | } 20 | double tmp = pow(x, n / 2); 21 | if( n % 2 == 0){ 22 | return tmp * tmp; 23 | }else{ 24 | if( n > 0){ 25 | return tmp * tmp * x; 26 | }else{ 27 | return tmp * tmp / x; 28 | } 29 | } 30 | } 31 | 32 | ///iterative 33 | double powi(double x, int n){ 34 | double ret = 1; 35 | long nn = n; 36 | if(n < 0 ){ 37 | nn = ~(nn - 1); 38 | } 39 | while(nn > 0){ 40 | if((nn & 1) == 1){ 41 | ret *= x; 42 | } 43 | x = x*x; 44 | nn = nn >> 1; 45 | } 46 | if(n < 0 ){ 47 | ret = 1 / ret; 48 | } 49 | return ret; 50 | } 51 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Unique Binary Search Trees II.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; left = null; right = null; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList generateTrees(int n) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | return generate(1,n); 15 | } 16 | 17 | ArrayList generate(int start, int end){ 18 | ArrayList results = new ArrayList(); 19 | if(start > end){ 20 | results.add(null); 21 | return results; 22 | } 23 | for(int i = start; i <= end; i++){ 24 | ArrayList lefts = generate(start,i-1); 25 | ArrayList rights = generate(i+1,end); 26 | for(TreeNode left : lefts){ 27 | for(TreeNode right : rights){ 28 | TreeNode node = new TreeNode(i); 29 | node.left = left; 30 | node.right = right; 31 | results.add(node); 32 | } 33 | } 34 | } 35 | return results; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /leetCode/Leetcode/Convert Sorted Array to Binary Search Tree.txt: -------------------------------------------------------------------------------- 1 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 2 | 3 | =============================== 4 | 5 | be careful of the index of middle, start + len / 2 6 | 7 | Solution: 8 | 9 | /** 10 | * Definition for binary tree 11 | * public class TreeNode { 12 | * int val; 13 | * TreeNode left; 14 | * TreeNode right; 15 | * TreeNode(int x) { val = x; } 16 | * } 17 | */ 18 | public class Solution { 19 | public TreeNode sortedArrayToBST(int[] num) { 20 | // Start typing your Java solution below 21 | // DO NOT write main() function 22 | if(num.length == 0){ 23 | return null; 24 | } 25 | return build(num,0,num.length -1); 26 | } 27 | 28 | TreeNode build(int[] num, int start, int end){ 29 | if(start == end){ 30 | TreeNode node = new TreeNode(num[start]); 31 | return node; 32 | } 33 | if( start > end){ 34 | return null; 35 | } 36 | int mid = (end - start) / 2 + start; 37 | TreeNode node = new TreeNode(num[mid]); 38 | node.left = build(num,start,mid-1); 39 | node.right = build(num,mid+1,end); 40 | return node; 41 | } 42 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Distinct Subsequences.txt: -------------------------------------------------------------------------------- 1 | Given a string S and a string T, count the number of distinct subsequences of T in S. 2 | 3 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). 4 | 5 | Here is an example: 6 | S = "rabbbit", T = "rabbit" 7 | 8 | Return 3. 9 | 10 | ===================================== 11 | get results from right to left. 12 | 13 | 14 | because use one array to store the results.so have to iterate from right to left 15 | 16 | public class Solution { 17 | public int numDistinct(String S, String T) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | if(S.length() < T.length() ){ 21 | return 0; 22 | } 23 | int n = S.length(); 24 | int m = T.length(); 25 | int[] res = new int[m+1]; 26 | res[0] = 1; 27 | for(int i = 1 ; i <= n; i++){ 28 | for(int j = m ; j >= 1; j--){ 29 | if(S.charAt(i-1) == T.charAt(j-1)){ 30 | res[j] += res[j-1]; 31 | } 32 | } 33 | } 34 | return res[m]; 35 | } 36 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Remove Duplicates from Sorted List.txt: -------------------------------------------------------------------------------- 1 | Given a sorted linked list, delete all duplicates such that each element appear only once. 2 | 3 | For example, 4 | Given 1->1->2, return 1->2. 5 | Given 1->1->2->3->3, return 1->2->3. 6 | 7 | ================================= 8 | 9 | implement next function 10 | 11 | Solution: 12 | 13 | /** 14 | * Definition for singly-linked list. 15 | * public class ListNode { 16 | * int val; 17 | * ListNode next; 18 | * ListNode(int x) { 19 | * val = x; 20 | * next = null; 21 | * } 22 | * } 23 | */ 24 | public class Solution { 25 | public ListNode deleteDuplicates(ListNode head) { 26 | // Start typing your Java solution below 27 | // DO NOT write main() function 28 | if(head == null){ 29 | return null; 30 | } 31 | ListNode tail = head; 32 | while((tail.next = next(tail)) != null){ 33 | tail = tail.next; 34 | } 35 | return head; 36 | } 37 | 38 | ListNode next(ListNode node){ 39 | if(node == null){return node;} 40 | int tmp = node.val; 41 | while(node != null){ 42 | if(node.val > tmp){ 43 | return node; 44 | } 45 | node = node.next; 46 | } 47 | return null; 48 | } 49 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Subsets.txt: -------------------------------------------------------------------------------- 1 | Given a set of distinct integers, S, return all possible subsets. 2 | 3 | Note: 4 | 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | For example, 8 | If S = [1,2,3], a solution is: 9 | 10 | [ 11 | [3], 12 | [1], 13 | [2], 14 | [1,2,3], 15 | [1,3], 16 | [2,3], 17 | [1,2], 18 | [] 19 | ] 20 | 21 | ============================= 22 | 23 | take care : use new ArrayList to load the sets 24 | 25 | Solution : 26 | 27 | public class Solution { 28 | public ArrayList> subsets(int[] S) { 29 | // Start typing your Java solution below 30 | // DO NOT write main() function 31 | ArrayList> res = new ArrayList>(); 32 | res.add(new ArrayList()); 33 | if(S.length == 0){ 34 | return res; 35 | } 36 | Arrays.sort(S); 37 | for(int i = 0 ; i < S.length; i++){ 38 | ArrayList> tmps = new ArrayList>(res); 39 | for(ArrayList tmp : tmps){ 40 | ArrayList ntmp = new ArrayList(tmp); 41 | ntmp.add(S[i]); 42 | res.add(ntmp); 43 | } 44 | } 45 | return res; 46 | } 47 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Remove Duplicates from Sorted List II.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode deleteDuplicates(ListNode head) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | if(head == null){ 17 | return head; 18 | } 19 | ListNode k = head; 20 | ListNode tail = null; 21 | ListNode res = null; 22 | while(k!= null){ 23 | if(k.next == null || k.next.val != k.val){ 24 | if(tail == null){ 25 | tail = k; 26 | res = k; 27 | }else{ 28 | tail.next = k; 29 | tail = tail.next; 30 | } 31 | k = k.next; 32 | }else{ 33 | //find next 34 | int tmp = k.val; 35 | while(k != null && k.val == tmp){ 36 | k = k.next; 37 | } 38 | } 39 | } 40 | if(tail != null){ 41 | tail.next = null; 42 | } 43 | return res; 44 | } 45 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Search a 2D Matrix.txt: -------------------------------------------------------------------------------- 1 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 2 | 3 | Integers in each row are sorted from left to right. 4 | The first integer of each row is greater than the last integer of the previous row. 5 | For example, 6 | 7 | Consider the following matrix: 8 | 9 | [ 10 | [1, 3, 5, 7], 11 | [10, 11, 16, 20], 12 | [23, 30, 34, 50] 13 | ] 14 | 15 | ========================================= 16 | 17 | 18 | Solution: 19 | 20 | public class Solution { 21 | public boolean searchMatrix(int[][] matrix, int target) { 22 | // Start typing your Java solution below 23 | // DO NOT write main() function 24 | int n = matrix.length; 25 | if(n == 0){ 26 | return false; 27 | } 28 | int m = matrix[0].length; 29 | int low =0; 30 | int high = n*m -1; 31 | while(low <= high){ 32 | int mid = low + (high - low) /2; 33 | int x = mid / m; 34 | int y = mid % m; 35 | if(matrix[x][y] == target){ 36 | return true; 37 | }else if(matrix[x][y] > target){ 38 | high = mid -1; 39 | }else{ 40 | low = mid + 1; 41 | } 42 | } 43 | return false; 44 | } 45 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/First Missing Positive.txt: -------------------------------------------------------------------------------- 1 | Given an unsorted integer array, find the first missing positive integer. 2 | 3 | For example, 4 | Given [1,2,0] return 3, 5 | and [3,4,-1,1] return 2. 6 | 7 | Your algorithm should run in O(n) time and uses constant space. 8 | 9 | ============================================= 10 | be careful of the terminal condition in while 11 | when cur number bigger than n or small than 1 or eqauls to A[cur -1] terminate 12 | 13 | 14 | Solution: 15 | 16 | public class Solution { 17 | public int firstMissingPositive(int[] A) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | if(A.length == 0){ 21 | return 1; 22 | } 23 | int n = A.length; 24 | for(int i = 0 ; i < n; i++){ 25 | if(A[i] <= 0 || A[i] > n || A[i] == i + 1){ 26 | continue; 27 | } 28 | int ti = i; 29 | while(A[i] > 0 && A[i] <= n && A[i] != A[A[i] - 1]){ 30 | int tmp = A[A[i] - 1]; 31 | A[A[i] -1] = A[i]; 32 | A[i] = tmp; 33 | } 34 | i = ti; 35 | } 36 | 37 | for(int i = 0 ; i < n; i++){ 38 | if( A[i] != i+1){ 39 | return i+1; 40 | } 41 | } 42 | return n + 1; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /leetCode/Leetcode/Remove Element.txt: -------------------------------------------------------------------------------- 1 | Given an array and a value, remove all instances of that value in place and return the new length. 2 | 3 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 4 | 5 | 6 | ==================================== 7 | 8 | 9 | Solution: 10 | 11 | public class Solution { 12 | public int removeElement(int[] num, int elem) { 13 | // Start typing your Java solution below 14 | // DO NOT write main() function 15 | int pe = nextElem(num,elem,num.length -1);; 16 | int pn = next(num,elem,num.length -1);; 17 | while(pe >= 0){ 18 | if(pn == -1){return 0;} 19 | if(pn < pe){ 20 | pe = nextElem(num,elem,pe-1); 21 | continue; 22 | } 23 | num[pe] = num[pn]; 24 | pe = nextElem(num,elem,pe-1); 25 | pn = next(num,elem,pn-1); 26 | } 27 | return pn+1; 28 | } 29 | 30 | int nextElem(int[] num,int elem,int index){ 31 | for(int i = index; i >= 0 ; i--){ 32 | if(num[i] == elem){return i;} 33 | } 34 | return -1; 35 | } 36 | 37 | int next(int[] num,int elem,int index){ 38 | for(int i = index ; i >= 0 ; i--){ 39 | if(num[i] != elem){return i;} 40 | } 41 | return -1; 42 | } 43 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Search in Rotated Sorted Array.txt: -------------------------------------------------------------------------------- 1 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 2 | 3 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 4 | 5 | You are given a target value to search. If found in the array return its index, otherwise return -1. 6 | 7 | You may assume no duplicate exists in the array. 8 | 9 | ====================== 10 | 11 | 12 | 13 | Solution: 14 | 15 | 16 | public class Solution { 17 | public int search(int[] A, int target) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | if(A.length == 0){ 21 | return -1; 22 | } 23 | int low = 0; 24 | int high = A.length -1; 25 | while(low <= high){ 26 | int mid = low + (high - low) / 2; 27 | if(target == A[mid]){ 28 | return mid; 29 | }else if(A[mid] >= A[low]){ 30 | if(target >= A[low] && target < A[mid]){ 31 | high = mid -1; 32 | }else{ 33 | low = mid + 1; 34 | } 35 | }else{ 36 | if(target > A[mid] && target <= A[high]){ 37 | low = mid + 1; 38 | }else{ 39 | high = mid -1; 40 | } 41 | } 42 | } 43 | return -1; 44 | } 45 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Implement strStr().txt: -------------------------------------------------------------------------------- 1 | Implement strStr(). 2 | 3 | Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 4 | 5 | ========================================================= 6 | 7 | Complexity : (O(mn)) 8 | 9 | please take care of the "" string. 10 | 11 | 1. "" , "" -- "" 12 | 2. "", "a" -- null 13 | 3. "a","" -- "a" 14 | 15 | public class Solution { 16 | public String strStr(String haystack, String needle) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | if(needle.length() == 0){ 20 | return haystack; 21 | } 22 | if(haystack.length() < needle.length() || haystack.length() == 0){ 23 | return null; 24 | } 25 | for(int i = 0 ; i <= haystack.length() - needle.length(); i++){ 26 | int index = 0; 27 | int tmp = i; 28 | if(haystack.charAt(i) != needle.charAt(index)){ 29 | continue; 30 | } 31 | while(tmp < haystack.length() && index < needle.length() && haystack.charAt(tmp) == needle.charAt(index)){ 32 | tmp++; 33 | index++; 34 | } 35 | if(index == needle.length()){ 36 | return haystack.substring(i); 37 | } 38 | } 39 | return null; 40 | } 41 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Letter Combinations of a Phone Number.txt: -------------------------------------------------------------------------------- 1 | Given a digit string, return all possible letter combinations that the number could represent. 2 | 3 | A mapping of digit to letters (just like on the telephone buttons) is given below. 4 | Input:Digit string "23" 5 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 6 | 7 | =========================== 8 | 9 | when input is "" output should be "" too. 10 | 11 | Solutions: 12 | 13 | public class Solution { 14 | public ArrayList letterCombinations(String digits) { 15 | // Start typing your Java solution below 16 | // DO NOT write main() function 17 | ArrayList res = new ArrayList(); 18 | if(digits.length() == 0){ 19 | res.add(""); 20 | return res; 21 | } 22 | String[] words = new String[]{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 23 | dfs(digits,0,"",res,words); 24 | return res; 25 | } 26 | 27 | void dfs(String digits,int index,String add,ArrayList res,String[] words){ 28 | if(index == digits.length()){ 29 | res.add(add); 30 | return; 31 | } 32 | String word = words[digits.charAt(index) - '0' - 2]; 33 | for(int i = 0 ; i < word.length(); i++){ 34 | dfs(digits,index+1,add+word.charAt(i),res,words); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Longest Substring Without Repeating Characters.txt: -------------------------------------------------------------------------------- 1 | Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. 2 | ========================================================= 3 | 4 | Complexity: O(n) 5 | 6 | Version: 2nd 7 | 8 | Solution: 9 | 10 | public class Solution { 11 | public int lengthOfLongestSubstring(String s) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | if(s == null || s.length() == 0){ 15 | return 0; 16 | } 17 | int[] checks = new int[26]; 18 | for(int i = 0 ; i < 26; i++){ 19 | checks[i] = -1; 20 | } 21 | int max = 0; 22 | int left = 0; 23 | for(int i = 0 ; i < s.length();i++){ 24 | if(checks[s.charAt(i) - 'a'] != -1){ 25 | //important to find the max 26 | // because the postion of repeated character may head of left. 27 | left = Math.max(checks[s.charAt(i) - 'a'] + 1,left); 28 | } 29 | checks[s.charAt(i) - 'a'] = i; 30 | if(i - left + 1 > max){ 31 | max = i - left +1; 32 | } 33 | } 34 | return max; 35 | } 36 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/N-Queens II.txt: -------------------------------------------------------------------------------- 1 | Follow up for N-Queens problem. 2 | 3 | Now, instead outputting board configurations, return the total number of distinct solutions. 4 | 5 | 6 | =========================================== 7 | 8 | Solution: 9 | 10 | 11 | public class Solution { 12 | 13 | class res { 14 | int res = 0; 15 | } 16 | public int totalNQueens(int n) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | res res = new res(); 20 | if(n <= 0){ 21 | return 0; 22 | } 23 | 24 | int[] queens = new int[n]; 25 | dfs(queens,0,res); 26 | return res.res; 27 | } 28 | 29 | void dfs(int[] queens,int index,res res){ 30 | if(index == queens.length){ 31 | res.res++; 32 | return; 33 | } 34 | for(int i = 0; i < queens.length; i++){ 35 | queens[index] = i; 36 | if(valid(queens,index)){ 37 | dfs(queens,index+1,res); 38 | } 39 | } 40 | return; 41 | } 42 | boolean valid(int[] queens,int index){ 43 | for(int i = 0 ; i < index; i++){ 44 | if(queens[i] == queens[index] || Math.abs(i - index) == Math.abs(queens[i] - queens[index])){ 45 | return false; 46 | } 47 | } 48 | return true; 49 | } 50 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Divide Two Integers.txt: -------------------------------------------------------------------------------- 1 | Divide two integers without using multiplication, division and mod operator. 2 | 3 | 4 | ================================== 5 | 6 | 1. be careful of sign of the two integer. 7 | 2. be careful of the divisor == 0 8 | 3. be careful of overflow when change Integer.MIN_VALUE to positive 9 | 10 | Solution: 11 | 12 | public class Solution { 13 | public int divide(int dividend, int divisor) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | // be careful of positive and negative integer 17 | if(dividend == 0 || divisor == 0 ){ 18 | return 0; 19 | } 20 | long dend = dividend; 21 | long sor = divisor; 22 | boolean neg = false; 23 | if(dividend < 0){ 24 | neg = neg == true?false:true; 25 | dend = ~(dend - 1); 26 | } 27 | if(sor < 0){ 28 | neg = neg == true?false:true; 29 | sor = ~(sor -1); 30 | } 31 | int res = 0; 32 | int bits = 0; 33 | while(dend >= (sor << bits)){ bits++;} 34 | bits--; 35 | while( bits >= 0){ 36 | if( dend - (sor << bits) >= 0){ 37 | dend = dend - (sor << bits); 38 | res += 1 << bits; 39 | } 40 | bits--; 41 | } 42 | return neg?~ (res - 1):res; 43 | } 44 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Maximal Rectangle .txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maximalRectangle(char[][] matrix) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int m = matrix.length; 6 | if(m == 0){ 7 | return 0; 8 | } 9 | int n = matrix[0].length; 10 | int res = 0; 11 | int[] height = new int[n]; 12 | int[] left = new int[n]; 13 | int[] right = new int[n]; 14 | for(int i = 0 ; i < n ; i++){ 15 | right[i] = n; 16 | } 17 | for(int i = 0 ; i < m; i++){ 18 | int l = 0;int r = n; 19 | for(int j = 0 ; j < n; j++){ 20 | if(matrix[i][j] == '0'){ 21 | height[j] = 0; 22 | left[j] = 0; 23 | l = j + 1; 24 | right[j] = n; 25 | }else{ 26 | height[j]++; 27 | left[j] = Math.max(left[j],l); 28 | } 29 | } 30 | for(int j = n - 1; j >= 0; j--){ 31 | if(matrix[i][j] == '0'){ 32 | r = j; 33 | }else{ 34 | right[j] = Math.min(right[j],r); 35 | res = Math.max(res,height[j] * (right[j] - left[j])); 36 | } 37 | } 38 | } 39 | return res; 40 | } 41 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Symmetric Tree.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 2 | 3 | For example, this binary tree is symmetric: 4 | 5 | 1 6 | / \ 7 | 2 2 8 | / \ / \ 9 | 3 4 4 3 10 | But the following is not: 11 | 12 | 1 13 | / \ 14 | 2 2 15 | \ \ 16 | 3 3 17 | Note: 18 | Bonus points if you could solve it both recursively and iteratively. 19 | 20 | ================================= 21 | 22 | just recurrence solution 23 | 24 | Solution: 25 | 26 | /** 27 | * Definition for binary tree 28 | * public class TreeNode { 29 | * int val; 30 | * TreeNode left; 31 | * TreeNode right; 32 | * TreeNode(int x) { val = x; } 33 | * } 34 | */ 35 | public class Solution { 36 | public boolean isSymmetric(TreeNode root) { 37 | // Start typing your Java solution below 38 | // DO NOT write main() function 39 | if(root == null){ 40 | return true; 41 | } 42 | return match(root.left,root.right); 43 | } 44 | 45 | Boolean match(TreeNode left, TreeNode right){ 46 | if(left == null){ 47 | return right == null; 48 | } 49 | if(right == null){ 50 | return left == null; 51 | } 52 | if(left.val != right.val){ 53 | return false; 54 | } 55 | return match(left.left,right.right) && match(left.right,right.left); 56 | } 57 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Permutations.txt: -------------------------------------------------------------------------------- 1 | Given a collection of numbers, return all possible permutations. 2 | 3 | For example, 4 | [1,2,3] have the following permutations: 5 | [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. 6 | 7 | ==================================== 8 | 9 | 10 | Solution: 11 | 12 | public class Solution { 13 | public ArrayList> permute(int[] num) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | ArrayList> res = new ArrayList>(); 17 | if(num == null || num.length == 0){ 18 | return res; 19 | } 20 | ArrayList adds = new ArrayList(); 21 | dfs(num,0,adds,res); 22 | return res; 23 | } 24 | 25 | void dfs(int[] num, int index, ArrayList adds,ArrayList> res){ 26 | if(index == num.length){ 27 | res.add(new ArrayList(adds)); 28 | return; 29 | } 30 | for(int i = index; i < num.length; i++){ 31 | swap(num,index,i); 32 | adds.add(num[index]); 33 | dfs(num,index+1,adds,res); 34 | swap(num,index,i); 35 | adds.remove(adds.size() -1); 36 | } 37 | } 38 | 39 | void swap(int[] num, int ia, int ib){ 40 | int tmp = num[ia]; 41 | num[ia] = num[ib]; 42 | num[ib] = tmp; 43 | } 44 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Validate Binary Search Tree.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isValidBST(TreeNode root) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | //byinOrder(root); 15 | return byMaxAndMin(root,null,null); 16 | } 17 | 18 | boolean byMaxAndMin(TreeNode node,Integer max, Integer min){ 19 | if(node == null){ 20 | return true; 21 | } 22 | if((max != null && node.val >= max) || (min != null && node.val <= min)){ 23 | return false; 24 | } 25 | return byMaxAndMin(node.left,node.val,min) && byMaxAndMin(node.right,max,node.val); 26 | } 27 | 28 | boolean byinOrder(TreeNode root){ 29 | ArrayList res = new ArrayList(); 30 | inOrder(root,res); 31 | for(int i = 0 ; i < res.size(); i++){ 32 | if(i != 0 && res.get(i) <= res.get(i -1)){ 33 | return false; 34 | } 35 | } 36 | return true; 37 | } 38 | 39 | void inOrder(TreeNode node, ArrayList res){ 40 | if(node == null){ 41 | return; 42 | } 43 | inOrder(node.left,res); 44 | res.add(node.val); 45 | inOrder(node.right,res); 46 | } 47 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Anagrams.txt: -------------------------------------------------------------------------------- 1 | Given an array of strings, return all groups of strings that are anagrams. 2 | 3 | Note: All inputs will be in lower-case. 4 | 5 | ================================ 6 | 7 | abcc ccba cbac is anagrams. 8 | 9 | Complexity : O(n) space O(n) 10 | 11 | use hashmap to record the string after sort by chars 12 | 13 | Solution: 14 | 15 | public class Solution { 16 | public ArrayList anagrams(String[] strs) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | ArrayList res = new ArrayList(); 20 | if(strs.length <= 1){return res;} 21 | Map> checks = new HashMap>(); 22 | 23 | for(int i = 0 ; i < strs.length; i++){ 24 | char[] arrs = strs[i].toCharArray(); 25 | Arrays.sort(arrs); 26 | String nstr = new String(arrs); 27 | if(checks.containsKey(nstr)){ 28 | checks.get(nstr).add(i); 29 | }else{ 30 | List tmps = new ArrayList(); 31 | tmps.add(i); 32 | checks.put(nstr,tmps); 33 | } 34 | } 35 | for(String t : checks.keySet()){ 36 | List tmps = checks.get(t); 37 | if(tmps.size() <= 1){continue;} 38 | for(Integer index : tmps){ 39 | res.add(strs[index]); 40 | } 41 | } 42 | return res; 43 | } 44 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Sqrt(x).txt: -------------------------------------------------------------------------------- 1 | Implement int sqrt(int x). 2 | 3 | Compute and return the square root of x. 4 | 5 | ==================== 6 | 7 | Complexity O(logn) 8 | 9 | take care 10 | 11 | 1. +/- 12 | 2. if x is Integer.MIN_VALUE, should use long to instead it, or will underflow 13 | 14 | Solution: 15 | 16 | public class Solution { 17 | public int sqrt(int x) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | long xx = x; 21 | boolean sign = false; 22 | if(x <= 1 && x >= 0) {return x;}; 23 | if(x < 0){ 24 | xx = -1 * xx; 25 | sign = true; 26 | } 27 | long left = 1; 28 | long right = xx; 29 | 30 | while(left < right){ 31 | if(valid(xx,left)){return (int)left * (sign?-1:1);} 32 | if(valid(xx,right)){return (int)right * (sign?-1:1);} 33 | long mid = left + (right - left) / 2; 34 | if(valid(xx,mid)){ 35 | return (int)mid * (sign?-1:1); 36 | }else if(mid * mid < xx){ 37 | left = mid+1; 38 | }else{ 39 | right = mid -1; 40 | } 41 | } 42 | return (int)left * (sign?-1:1); 43 | } 44 | 45 | boolean valid(long x, long num){ 46 | if(num * num == x){ 47 | return true; 48 | }else if(num * num < x && (num+1) * (num+1) >x){ 49 | return true; 50 | } 51 | return false; 52 | } 53 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Edit Distance.txt: -------------------------------------------------------------------------------- 1 | Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) 2 | 3 | You have the following 3 operations permitted on a word: 4 | 5 | a) Insert a character 6 | b) Delete a character 7 | c) Replace a character 8 | 9 | 10 | ====================================================be careful of the 11 | index in the result loop (for word , index = index -1) 12 | 13 | 14 | Solution: 15 | 16 | public class Solution { 17 | public int minDistance(String word1, String word2) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | int n = word1.length(); 21 | int m = word2.length(); 22 | if(n == 0 || m == 0){ 23 | return n == 0?m:n; 24 | } 25 | int[][] res = new int[n+1][m+1]; 26 | for(int i = 0 ; i <= m;i++){ 27 | res[0][i] = i; 28 | } 29 | for(int i = 0 ; i <= n; i++){ 30 | res[i][0] = i; 31 | } 32 | for(int i = 1; i <= n ; i++){ 33 | for(int j = 1; j <= m ;j++){ 34 | if(word1.charAt(i -1) == word2.charAt(j-1)){ 35 | res[i][j] =Math.min(res[i][j-1] + 1, Math.min(res[i-1][j-1],res[i-1][j]+1)); 36 | }else{ 37 | res[i][j] = Math.min(res[i-1][j-1],Math.min(res[i-1][j],res[i][j-1])) + 1; 38 | } 39 | } 40 | } 41 | return res[n][m]; 42 | } 43 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Construct Binary Tree from Inorder and Postorder Traversal.txt: -------------------------------------------------------------------------------- 1 | Given inorder and postorder traversal of a tree, construct the binary tree. 2 | 3 | Note: 4 | You may assume that duplicates do not exist in the tree. 5 | 6 | ======================== 7 | 8 | Solution: 9 | 10 | /** 11 | * Definition for binary tree 12 | * public class TreeNode { 13 | * int val; 14 | * TreeNode left; 15 | * TreeNode right; 16 | * TreeNode(int x) { val = x; } 17 | * } 18 | */ 19 | public class Solution { 20 | public TreeNode buildTree(int[] inorder, int[] postorder) { 21 | // Start typing your Java solution below 22 | // DO NOT write main() function 23 | if(inorder.length != postorder.length){ 24 | return null; 25 | } 26 | return build(inorder,0,inorder.length -1,postorder,0,postorder.length -1); 27 | } 28 | 29 | TreeNode build(int[] in, int sin, int ein, int[] post, int sp,int ep){ 30 | if(sin == ein){ 31 | TreeNode node = new TreeNode(in[sin]); 32 | return node; 33 | } 34 | if(sin > ein){ 35 | return null; 36 | } 37 | int i = sin; 38 | for(i = sin; i <= ein; i++){ 39 | if(in[i] == post[ep]){ 40 | break; 41 | } 42 | } 43 | TreeNode node = new TreeNode(in[i]); 44 | node.left = build(in,sin,i-1,post,sp,sp + (i-1 - sin)); 45 | node.right = build(in,i+1,ein,post,sp + i -sin,ep-1); 46 | return node; 47 | } 48 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Construct Binary Tree from Preorder and Inorder Traversal.txt: -------------------------------------------------------------------------------- 1 | Given preorder and inorder traversal of a tree, construct the binary tree. 2 | 3 | Note: 4 | You may assume that duplicates do not exist in the tree. 5 | 6 | 7 | ======================================================== 8 | 9 | Solution: 10 | 11 | /** 12 | * Definition for binary tree 13 | * public class TreeNode { 14 | * int val; 15 | * TreeNode left; 16 | * TreeNode right; 17 | * TreeNode(int x) { val = x; } 18 | * } 19 | */ 20 | public class Solution { 21 | public TreeNode buildTree(int[] preorder, int[] inorder) { 22 | // Start typing your Java solution below 23 | // DO NOT write main() function 24 | if(preorder.length != inorder.length){ 25 | return null; 26 | } 27 | return build(preorder,0,preorder.length -1,inorder,0,inorder.length-1); 28 | } 29 | 30 | TreeNode build(int[] pre,int sp,int ep,int[] in, int si,int ei){ 31 | if(si == ei){ 32 | TreeNode node = new TreeNode(in[si]); 33 | return node; 34 | } 35 | if(si > ei){ 36 | return null; 37 | } 38 | int i = si; 39 | for(;i <= ei; i++){ 40 | if(in[i] == pre[sp]){ 41 | break; 42 | } 43 | } 44 | TreeNode node = new TreeNode(in[i]); 45 | node.left = build(pre,sp+1,sp + i - si,in,si,i-1); 46 | node.right = build(pre,sp+i-si+1,ep,in,i+1,ei); 47 | return node; 48 | } 49 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Path Sum.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 2 | 3 | For example: 4 | Given the below binary tree and sum = 22, 5 | 5 6 | / \ 7 | 4 8 8 | / / \ 9 | 11 13 4 10 | / \ \ 11 | 7 2 1 12 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 13 | 14 | ============================= 15 | 16 | be careful of the terminal condition: 17 | 18 | when node != null && node.left == null && node.right == null && node.val == sum 19 | return true; 20 | 21 | Solution: 22 | 23 | /** 24 | * Definition for binary tree 25 | * public class TreeNode { 26 | * int val; 27 | * TreeNode left; 28 | * TreeNode right; 29 | * TreeNode(int x) { val = x; } 30 | * } 31 | */ 32 | public class Solution { 33 | public boolean hasPathSum(TreeNode root, int sum) { 34 | // Start typing your Java solution below 35 | // DO NOT write main() function 36 | if(root == null){ 37 | return false; 38 | } 39 | return dfs(root,sum); 40 | } 41 | 42 | boolean dfs(TreeNode node, int sum){ 43 | if(node == null){ 44 | return false; 45 | } 46 | if(node.left == null && node.right == null && sum == node.val){ 47 | return true; 48 | } 49 | return dfs(node.left,sum - node.val) || dfs(node.right,sum-node.val); 50 | } 51 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Remove Nth Node From End of List.txt: -------------------------------------------------------------------------------- 1 | Given a linked list, remove the nth node from the end of list and return its head. 2 | 3 | For example, 4 | 5 | Given linked list: 1->2->3->4->5, and n = 2. 6 | 7 | After removing the second node from the end, the linked list becomes 1->2->3->5. 8 | Note: 9 | Given n will always be valid. 10 | Try to do this in one pass. 11 | 12 | ===================================== 13 | 14 | different with remove one node from a list. because the node can't the tail. 15 | 16 | record it's pre node. 17 | 18 | 19 | Solution: 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * public class ListNode { 24 | * int val; 25 | * ListNode next; 26 | * ListNode(int x) { 27 | * val = x; 28 | * next = null; 29 | * } 30 | * } 31 | */ 32 | public class Solution { 33 | public ListNode removeNthFromEnd(ListNode head, int n) { 34 | // Start typing your Java solution below 35 | // DO NOT write main() function 36 | if(head == null){ 37 | return null; 38 | } 39 | int times = n; 40 | ListNode k = head; 41 | ListNode tail = head; 42 | while(times > 0 && tail!=null){ 43 | tail = tail.next; 44 | times--; 45 | } 46 | if( tail == null){ 47 | return k.next; 48 | } 49 | while(tail.next != null){ 50 | tail = tail.next; 51 | k = k.next; 52 | } 53 | k.next = k.next.next; 54 | return head; 55 | } 56 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Median of Two Sorted Arrays.txt: -------------------------------------------------------------------------------- 1 | There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 2 | 3 | ========================= 4 | 5 | Complexity: O(log(m+n)) 6 | 7 | take care the terminal cases. 8 | 9 | 10 | 11 | Solution: 12 | 13 | 14 | 15 | public class Solution { 16 | public double findMedianSortedArrays(int A[], int B[]) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | int m = A.length; 20 | int n = B.length; 21 | if((m + n) % 2 == 1){ 22 | return find(A,0,m-1,B,0,n-1,(m+n)/2 + 1); 23 | }else{ 24 | return (find(A,0,m-1,B,0,n-1,(m+n)/2) + find(A,0,m-1,B,0,n-1,(m+n)/2+1)) / 2.0; 25 | } 26 | } 27 | 28 | int find(int[] a,int sa,int ea,int[] b, int sb,int eb,int k){ 29 | if(eb - sb > ea - sa){ 30 | return find(b,sb,eb,a,sa,ea,k); 31 | } 32 | if(sb > eb){ 33 | return a[sa + k - 1]; 34 | } 35 | if(k == 1){ 36 | return Math.min(a[sa],b[sb]); 37 | } 38 | int pb = Math.min(k / 2, eb - sb + 1); 39 | int pa = k - pb; 40 | if(a[sa + pa -1] == b[sb + pb -1]){ 41 | return a[sa + pa -1]; 42 | }else if(a[sa + pa -1] > b[sb+pb-1]){ 43 | return find(a,sa,ea,b,sb+pb,eb,k-pb); 44 | }else{ 45 | return find(a,sa+pa,ea,b,sb,eb,k-pa); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /leetCode/Version2.0/Search in Rotated Sorted Array.txt: -------------------------------------------------------------------------------- 1 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 2 | 3 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 4 | 5 | You are given a target value to search. If found in the array return its index, otherwise return -1. 6 | 7 | You may assume no duplicate exists in the array. 8 | 9 | ====================== 10 | 11 | 12 | 13 | Solution: 14 | 15 | 16 | public class Solution { 17 | public int search(int[] A, int target) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | if(A == null || A.length == 0){ 21 | return -1; 22 | } 23 | int low = 0; 24 | int high = A.length -1; 25 | while(low < high){ 26 | int mid = low + (high - low) / 2; 27 | if(A[mid] == target){ 28 | return mid; 29 | }else if(A[mid] > target){ 30 | if(A[high] < A[low] && A[mid] > A[high] && target <= A[high]){ 31 | low = mid + 1; 32 | }else{ 33 | high = mid - 1; 34 | } 35 | }else{ 36 | if(A[low] > A[high] && target > A[high] && A[mid] <= A[high]){ 37 | high = mid - 1; 38 | }else{ 39 | low = mid + 1; 40 | } 41 | } 42 | } 43 | if(A[low] != target ){ 44 | return -1; 45 | }else{ 46 | return low; 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Maximum Depth of Binary Tree.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int maxDepth(TreeNode root) { 12 | // Note: The Solution object is instantiated only once and is reused by each test case. 13 | return iterative(root); 14 | } 15 | 16 | int recursive(TreeNode node){ 17 | if(node == null){ 18 | return 0; 19 | } 20 | int left = recursive(node.left); 21 | int right = recursive(node.right); 22 | return Math.max(left,right) + 1; 23 | } 24 | 25 | int iterative(TreeNode node){ 26 | if(node == null){ 27 | return 0; 28 | } 29 | int level = 0; 30 | int current = 1; 31 | int next = 0; 32 | Queue ques = new LinkedList(); 33 | ques.add(node); 34 | while(ques.size() > 0){ 35 | TreeNode cur = ques.poll(); 36 | if(cur.left != null){ 37 | next++; 38 | ques.add(cur.left); 39 | } 40 | if(cur.right != null){ 41 | next ++; 42 | ques.add(cur.right); 43 | } 44 | current--; 45 | if(current == 0){ 46 | level++; 47 | current = next; 48 | next = 0; 49 | } 50 | } 51 | return level; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /leetCode/Leetcode/Sudoku Solver.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void solveSudoku(char[][] board) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | solve(board); 6 | } 7 | 8 | boolean solve(char[][] board){ 9 | for(int i = 0 ; i < board.length; i ++){ 10 | for(int j = 0 ; j < board.length; j++){ 11 | if(board[i][j] == '.'){ 12 | for(char k = '1'; k<= '9'; k++){ 13 | board[i][j] = k; 14 | if(valid(board,i,j) && solve(board)){ 15 | return true; 16 | } 17 | } 18 | board[i][j] = '.'; 19 | return false; 20 | } 21 | } 22 | } 23 | return true; 24 | } 25 | 26 | boolean valid(char[][] board,int x, int y){ 27 | for(int i = 0 ; i < board.length; i++){ 28 | if(i!=x && board[i][y] == board[x][y]){ 29 | return false; 30 | } 31 | if(i != y && board[x][i] == board[x][y]){ 32 | return false; 33 | } 34 | } 35 | int bx = x - x % 3; 36 | int by = y - y % 3; 37 | for(int i=0; i < 3; i++){ 38 | for(int j = 0 ; j < 3; j++){ 39 | if(x != (i + bx) && y != (j + by) && board[x][y] == board[i + bx][j + by]){ 40 | return false; 41 | } 42 | } 43 | } 44 | return true; 45 | } 46 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Add Two Numbers.txt: -------------------------------------------------------------------------------- 1 | You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 2 | 3 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 4 | Output: 7 -> 0 -> 8 5 | 6 | ========================================== 7 | 8 | Complexity O(m + n) 9 | 10 | Solution: 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * public class ListNode { 15 | * int val; 16 | * ListNode next; 17 | * ListNode(int x) { 18 | * val = x; 19 | * next = null; 20 | * } 21 | * } 22 | */ 23 | public class Solution { 24 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 25 | // Start typing your Java solution below 26 | // DO NOT write main() function 27 | ListNode head = null; 28 | ListNode tail = null; 29 | int add = 0; 30 | while(l1 != null || l2 != null){ 31 | int tmp = add; 32 | if(l1 != null){tmp += l1.val;l1 = l1.next;} 33 | if(l2 != null){tmp += l2.val;l2 = l2.next;} 34 | add = tmp / 10; 35 | tmp = tmp % 10; 36 | ListNode node = new ListNode(tmp); 37 | if(head == null){ 38 | head = node; tail = node; 39 | }else{ 40 | tail.next = node;tail = tail.next; 41 | } 42 | } 43 | if(add != 0){ 44 | ListNode node = new ListNode(add); 45 | tail.next = node; 46 | } 47 | return head; 48 | } 49 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Interleaving String.txt: -------------------------------------------------------------------------------- 1 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 2 | 3 | For example, 4 | Given 5 | s1 = aabcc, 6 | s2 = dbbca, 7 | 8 | When s3 = aadbbcbcac, return true. 9 | When s3 = aadbbbaccc, return false. 10 | 11 | ===================================== 12 | 13 | be careful of the initialization status 14 | 15 | Solution: 16 | 17 | public class Solution { 18 | public boolean isInterleave(String s1, String s2, String s3) { 19 | // Start typing your Java solution below 20 | // DO NOT write main() function 21 | if(s1.length() + s2.length() != s3.length()){ 22 | return false; 23 | } 24 | int n = s1.length(); 25 | int m = s2.length(); 26 | boolean[][] res = new boolean[n+1][m+1]; 27 | res[0][0] = true; 28 | for(int i = 1 ; i <= n ;i ++){ 29 | if(s1.charAt(i-1) == s3.charAt(i-1)){ 30 | res[i][0] = true; 31 | }else{ 32 | break; 33 | } 34 | } 35 | for(int i = 1; i <= m; i++){ 36 | if(s2.charAt(i -1) == s3.charAt(i-1)){ 37 | res[0][i] = true; 38 | } else{ 39 | break; 40 | } 41 | } 42 | for(int i = 1 ; i <= n; i++){ 43 | for(int j = 1 ; j <= m; j++){ 44 | res[i][j] = (s1.charAt(i-1) == s3.charAt(i+j-1) && res[i-1][j]) || 45 | (s2.charAt(j-1) == s3.charAt(i+j-1) && res[i][j-1]); 46 | } 47 | } 48 | return res[n][m]; 49 | } 50 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/3Sum Closest.txt: -------------------------------------------------------------------------------- 1 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 2 | 3 | For example, given array S = {-1 2 1 -4}, and target = 1. 4 | 5 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 6 | 7 | ======================================== 8 | 9 | 10 | beware of the initial of result 11 | 12 | result = num[0] + num[1] + num[2]; 13 | 14 | Solution: 15 | 16 | public class Solution { 17 | public int threeSumClosest(int[] num, int target) { 18 | // Start typing your Java solution below 19 | // DO NOT write main() function 20 | if(num == null || num.length <= 2){ 21 | return 0; 22 | } 23 | Arrays.sort(num); 24 | int min = num[0] + num[1] + num[2]; 25 | for(int i = 0 ; i < num.length -2; i++){ 26 | if( i != 0 && num[i] == num[i - 1]){continue;} 27 | int low = i + 1; 28 | int high = num.length -1; 29 | while(low < high ){ 30 | int sum = num[i] + num[low] + num[high]; 31 | if(Math.abs(sum - target) < Math.abs(min - target)){ 32 | min = sum ; 33 | } 34 | if(sum == target){ 35 | return target; 36 | }else if(sum < target){ 37 | low ++; 38 | }else{ 39 | high--; 40 | } 41 | } 42 | } 43 | return min; 44 | } 45 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Spiral Matrix.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList spiralOrder(int[][] matrix) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | ArrayList res = new ArrayList(); 6 | int n = matrix.length; 7 | if(n == 0){ 8 | return res; 9 | } 10 | int m = matrix[0].length; 11 | int level = 0; 12 | while(n > 0 && m > 0){ 13 | if( n == 1){ 14 | for(int i = 0 ; i < m; i++){ 15 | res.add(matrix[level][level + i]); 16 | } 17 | }else if(m == 1){ 18 | for(int i = 0 ; i < n;i++){ 19 | res.add(matrix[level + i][level]); 20 | } 21 | }else{ 22 | ///top 23 | for(int i= 0 ; i < m -1; i++){ 24 | res.add(matrix[level][level + i]); 25 | } 26 | ///right 27 | for(int i = 0 ; i < n -1; i++){ 28 | res.add(matrix[level + i][level + m -1]); 29 | } 30 | ///bottom 31 | for(int i = 0; i < m - 1 ; i++){ 32 | res.add(matrix[level + n-1][level + m-1 - i]); 33 | } 34 | //left 35 | for(int i = 0 ; i < n - 1; i++){ 36 | res.add(matrix[level + n-1 - i][level]); 37 | } 38 | } 39 | level++; 40 | n -= 2; 41 | m -= 2; 42 | } 43 | return res; 44 | } 45 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Permutations II.txt: -------------------------------------------------------------------------------- 1 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 2 | 3 | For example, 4 | [1,1,2] have the following unique permutations: 5 | [1,1,2], [1,2,1], and [2,1,1]. 6 | 7 | ================================== 8 | 9 | use a hashset to check the replicate item 10 | 11 | Solution: 12 | public class Solution { 13 | public ArrayList> permuteUnique(int[] num) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | ArrayList> res = new ArrayList>(); 17 | if(num == null || num.length == 0){ 18 | return res; 19 | } 20 | ArrayList adds = new ArrayList(); 21 | dfs(num,0,adds,res); 22 | return res; 23 | } 24 | 25 | void dfs(int[] num, int index,ArrayList adds,ArrayList> res){ 26 | if(index == num.length ){ 27 | res.add(new ArrayList(adds)); 28 | return; 29 | } 30 | Set checks = new HashSet(); 31 | for(int i = index; i < num.length; i++){ 32 | if(checks.contains(num[i])){continue;} 33 | checks.add(num[i]); 34 | swap(num,index,i); 35 | adds.add(num[index]); 36 | dfs(num,index+1,adds,res); 37 | swap(num,index,i); 38 | adds.remove(adds.size() -1); 39 | } 40 | } 41 | 42 | void swap(int[] num, int ia,int ib){ 43 | int tmp = num[ia]; 44 | num[ia] = num[ib]; 45 | num[ib] = tmp; 46 | } 47 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Reverse Integer.txt: -------------------------------------------------------------------------------- 1 | Reverse digits of an integer. 2 | 3 | Example1: x = 123, return 321 4 | Example2: x = -123, return -321 5 | 6 | Have you thought about this? 7 | Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 8 | 9 | If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 10 | 11 | Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? 12 | 13 | Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter). 14 | 15 | ===================================================== 16 | 17 | be careful : 18 | 19 | 1. negative or positive 20 | 2. overflow or underflow 21 | 22 | Solution: 23 | 24 | public class Solution { 25 | public int reverse(int x) { 26 | // Start typing your Java solution below 27 | // DO NOT write main() function 28 | boolean neg = false; 29 | long num = x; 30 | if(x < 0){ 31 | neg = true; 32 | num = -1 * num; 33 | } 34 | long res = 0; 35 | while( num > 0){ 36 | res = res * 10 + num % 10; 37 | num = num / 10; 38 | } 39 | if(neg){ 40 | res = res * -1; 41 | } 42 | if(res < Integer.MIN_VALUE){ 43 | return Integer.MIN_VALUE; 44 | }else if(res > Integer.MAX_VALUE){ 45 | return Integer.MAX_VALUE; 46 | }else{ 47 | return (int)res; 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Longest Consecutive Sequence.txt: -------------------------------------------------------------------------------- 1 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 2 | 3 | For example, 4 | Given [100, 4, 200, 1, 3, 2], 5 | The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. 6 | 7 | Your algorithm should run in O(n) complexity. 8 | 9 | ============================ 10 | 11 | Complexity: space O(n) time : O(n) 12 | 13 | use a HashSet to store the nums, for each num check its upper and lower in loop 14 | be careful that, in the loop, if find one integer, remove it from the hashset to reduce repeated computation for other integers 15 | 16 | Solution: 17 | 18 | public class Solution { 19 | public int longestConsecutive(int[] num) { 20 | // Start typing your Java solution below 21 | // DO NOT write main() function 22 | if(num == null || num.length == 0){ 23 | return 0; 24 | } 25 | HashSet checks = new HashSet(); 26 | for(int n : num){ 27 | checks.add(n); 28 | } 29 | int max = 0; 30 | for(int i = 0 ; i < num.length;i++){ 31 | int tmp = num[i]; 32 | int left = 0; 33 | int right = 0; 34 | while(checks.contains(++tmp)){ 35 | left++; 36 | checks.remove(tmp-1); 37 | } 38 | tmp = num[i]; 39 | while(checks.contains(--tmp)){ 40 | right++; 41 | checks.remove(tmp+1); 42 | } 43 | if(max < left + right + 1){ 44 | max = left+right+1; 45 | } 46 | } 47 | return max; 48 | } 49 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Combinations.txt: -------------------------------------------------------------------------------- 1 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 2 | 3 | For example, 4 | If n = 4 and k = 2, a solution is: 5 | 6 | [ 7 | [2,4], 8 | [3,4], 9 | [2,3], 10 | [1,2], 11 | [1,3], 12 | [1,4], 13 | ] 14 | 15 | ============================================ 16 | 17 | take care, [1,2] and [2,1] is the same. different from permutations... 18 | just select index = i and from i + 1 get k -1 19 | 20 | Solutions: 21 | 22 | public class Solution { 23 | public ArrayList> combine(int n, int k) { 24 | // Start typing your Java solution below 25 | // DO NOT write main() function 26 | ArrayList> res = new ArrayList>(); 27 | if(k == 0){ 28 | return res; 29 | } 30 | int[] num = new int[n]; 31 | for(int i = 0 ; i < n; i++){ 32 | num[i] = i + 1; 33 | } 34 | ArrayList adds = new ArrayList(); 35 | select(num,0,k,adds,res); 36 | return res; 37 | } 38 | 39 | void select(int[] num, int index, int k,ArrayList adds,ArrayList> res){ 40 | if(k == 0){ 41 | res.add(new ArrayList(adds)); 42 | return; 43 | } 44 | for(int i = index; i < num.length; i++){ 45 | adds.add(num[i]); 46 | select(num,i+1,k-1,adds,res); 47 | adds.remove(adds.size() -1); 48 | } 49 | } 50 | 51 | void swap(int[] num, int ia, int ib){ 52 | int tmp = num[ia]; 53 | num[ia] = num[ib]; 54 | num[ib] = tmp; 55 | } 56 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Valid Palindrome.txt: -------------------------------------------------------------------------------- 1 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 2 | 3 | For example, 4 | "A man, a plan, a canal: Panama" is a palindrome. 5 | "race a car" is not a palindrome. 6 | 7 | Note: 8 | Have you consider that the string might be empty? This is a good question to ask during an interview. 9 | 10 | For the purpose of this problem, we define empty string as valid palindrome. 11 | 12 | ============================ 13 | 14 | Complexity : O(n) 15 | 16 | take care 17 | 1. "" -- true 18 | 2. "." -- true 19 | 3. "1a2" -- false 20 | 4. ".1.1" -- true 21 | 5. "aA" -- true 22 | 23 | 24 | Solution: 25 | 26 | public class Solution { 27 | public boolean isPalindrome(String s) { 28 | // Start typing your Java solution below 29 | // DO NOT write main() function 30 | if(s.length() <= 1){ 31 | return true; 32 | } 33 | int left = 0; 34 | int right = s.length() -1; 35 | while(left < right){ 36 | if(!valid(toLower(s.charAt(left)))){left++;continue;} 37 | if(!valid(toLower(s.charAt(right)))){right--;continue;} 38 | if(toLower(s.charAt(left)) == toLower(s.charAt(right))){ 39 | left++;right--; 40 | }else{ 41 | return false; 42 | } 43 | } 44 | return true; 45 | } 46 | 47 | boolean valid(char ch){ 48 | if((ch > 'z' || ch < 'a') && (ch < '0' || ch > '9')){return false;} 49 | return true; 50 | } 51 | char toLower(char ch){ 52 | if(ch >= 'A' && ch <= 'Z'){ch = (char)(ch + 32);} 53 | return ch; 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /leetCode/Leetcode/Binary Tree Maximum Path Sum.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, find the maximum path sum. 2 | 3 | The path may start and end at any node in the tree. 4 | 5 | For example: 6 | Given the below binary tree, 7 | 8 | 1 9 | / \ 10 | 2 3 11 | Return 6. 12 | 13 | ============================================================= 14 | 15 | be careful of the relationship between left, right and node 16 | for maxpath, the return value will be max(left,right) + node or node 17 | for result, the value will between left,right,left+node,right+node,left+right+node and original 18 | 19 | Solution: 20 | 21 | /** 22 | * Definition for binary tree 23 | * public class TreeNode { 24 | * int val; 25 | * TreeNode left; 26 | * TreeNode right; 27 | * TreeNode(int x) { val = x; } 28 | * } 29 | */ 30 | public class Solution { 31 | class res { 32 | int res = Integer.MIN_VALUE; 33 | } 34 | public int maxPathSum(TreeNode root) { 35 | // Start typing your Java solution below 36 | // DO NOT write main() function 37 | res res = new res(); 38 | if(root == null){ 39 | return res.res; 40 | } 41 | maxPath(root,res); 42 | return res.res; 43 | } 44 | 45 | int maxPath(TreeNode node,res res){ 46 | if(node == null){ 47 | return 0; 48 | } 49 | int left = maxPath(node.left,res); 50 | int right = maxPath(node.right,res); 51 | int max = Math.max(node.val,node.val + Math.max(left,right)); 52 | max = Math.max(max,right + node.val + left); 53 | res.res = Math.max(res.res,max); 54 | return Math.max(node.val,Math.max(left,right) + node.val); 55 | } 56 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Subsets II.txt: -------------------------------------------------------------------------------- 1 | Given a collection of integers that might contain duplicates, S, return all possible subsets. 2 | 3 | Note: 4 | 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | For example, 8 | If S = [1,2,2], a solution is: 9 | 10 | [ 11 | [2], 12 | [1], 13 | [1,2,2], 14 | [2,2], 15 | [1,2], 16 | [] 17 | ] 18 | 19 | ================================= 20 | use a variable last to record the count added to results in last round 21 | 22 | Solution: 23 | 24 | public class Solution { 25 | public ArrayList> subsetsWithDup(int[] num) { 26 | // Start typing your Java solution below 27 | // DO NOT write main() function 28 | ArrayList> res = new ArrayList>(); 29 | ArrayList adds = new ArrayList(); 30 | res.add(adds); 31 | if(num.length == 0){ 32 | return res; 33 | } 34 | int last = 0; 35 | Arrays.sort(num); 36 | for(int i = 0 ; i < num.length; i++){ 37 | int next = 0; 38 | ArrayList> tmps = new ArrayList>(res); 39 | for(ArrayList add : tmps){ 40 | if(i != 0 && num[i] == num[i -1] && last > 0){ 41 | last--; 42 | }else{ 43 | ArrayList tmp = new ArrayList(add); 44 | tmp.add(num[i]); 45 | res.add(tmp); 46 | next++; 47 | } 48 | } 49 | last = res.size() - next; 50 | } 51 | return res; 52 | } 53 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Substring with Concatenation of All Words.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList findSubstring(String S, String[] L) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | ArrayList res = new ArrayList(); 6 | if(L.length == 0){ 7 | return res; 8 | } 9 | HashMap counts = new HashMap(); 10 | for(String l : L){ 11 | if(counts.containsKey(l)){ 12 | counts.put(l,counts.get(l) + 1); 13 | }else{ 14 | counts.put(l,1); 15 | } 16 | } 17 | for(int i = 0 ; i <= S.length() - L.length * L[0].length(); i++){ 18 | HashMap tmps = new HashMap(); 19 | int number = 0; 20 | int size = L.length; 21 | for(int j = 0 ; j < size; j++){ 22 | String word = S.substring(i + L[0].length() * j , i + L[0].length() *(j+1)); 23 | if(counts.containsKey(word)){ 24 | if(tmps.containsKey(word) && tmps.get(word) >= counts.get(word)){ 25 | break; 26 | } 27 | if(!tmps.containsKey(word)){ 28 | tmps.put(word,1); 29 | }else{ 30 | tmps.put(word,tmps.get(word) + 1); 31 | } 32 | number++; 33 | }else{ 34 | break; 35 | } 36 | } 37 | if(number == L.length){ 38 | res.add(i); 39 | } 40 | } 41 | return res; 42 | } 43 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Palindrome Partitioning.txt: -------------------------------------------------------------------------------- 1 | Given a string s, partition s such that every substring of the partition is a palindrome. 2 | 3 | Return all possible palindrome partitioning of s. 4 | 5 | For example, given s = "aab", 6 | Return 7 | 8 | [ 9 | ["aa","b"], 10 | ["a","a","b"] 11 | ] 12 | 13 | =========================================== 14 | 15 | DFS 16 | 17 | Solution: 18 | 19 | public class Solution { 20 | public ArrayList> partition(String s) { 21 | // Start typing your Java solution below 22 | // DO NOT write main() function 23 | ArrayList> res = new ArrayList>(); 24 | if(s.length() == 0){ 25 | return res; 26 | } 27 | ArrayList adds = new ArrayList(); 28 | dfs(s,0,adds,res); 29 | return res; 30 | } 31 | 32 | void dfs(String s, int index,ArrayList adds,ArrayList> res){ 33 | if(index == s.length()){ 34 | res.add(new ArrayList(adds)); 35 | return; 36 | } 37 | for(int i = index + 1; i <= s.length() ;i++){ 38 | String nstr = s.substring(index,i); 39 | if(valid(nstr)){ 40 | adds.add(nstr); 41 | dfs(s,i,adds,res); 42 | adds.remove(adds.size() -1); 43 | } 44 | } 45 | } 46 | 47 | boolean valid(String str){ 48 | int left = 0; 49 | int right = str.length() -1; 50 | while(left < right){ 51 | if(str.charAt(left) != str.charAt(right)){ 52 | return false; 53 | } 54 | left++;right--; 55 | } 56 | return true; 57 | } 58 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Merge Two Sorted Lists.txt: -------------------------------------------------------------------------------- 1 | 2 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 3 | 4 | ========================================= 5 | 6 | Complexity space O(1) time O(m+n) 7 | 8 | take care l1 maybe null and l2 maybe null 9 | 10 | Solution: 11 | /** 12 | * Definition for singly-linked list. 13 | * public class ListNode { 14 | * int val; 15 | * ListNode next; 16 | * ListNode(int x) { 17 | * val = x; 18 | * next = null; 19 | * } 20 | * } 21 | */ 22 | public class Solution { 23 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 24 | // Start typing your Java solution below 25 | // DO NOT write main() function 26 | ListNode head = null; 27 | ListNode tail = null; 28 | while(l1 != null || l2 != null){ 29 | ListNode tmp = null; 30 | if( l1 != null){ 31 | tmp = l1; 32 | } 33 | if( l2 != null){ 34 | if(tmp == null){ 35 | tmp = l2; 36 | l2 = l2.next; 37 | }else{ 38 | if(tmp.val < l2.val){ 39 | l1 = l1.next; 40 | }else{ 41 | tmp = l2; 42 | l2 = l2.next; 43 | } 44 | } 45 | }else{ 46 | l1 = l1.next; 47 | } 48 | if(head == null){ 49 | head = tmp; 50 | tail = tmp; 51 | }else{ 52 | tail.next = tmp; 53 | tail = tail.next; 54 | } 55 | } 56 | return head; 57 | } 58 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Convert Sorted List to Binary Search Tree.txt: -------------------------------------------------------------------------------- 1 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 2 | 3 | =============================================== 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; next = null; } 11 | * } 12 | */ 13 | /** 14 | * Definition for binary tree 15 | * public class TreeNode { 16 | * int val; 17 | * TreeNode left; 18 | * TreeNode right; 19 | * TreeNode(int x) { val = x; } 20 | * } 21 | */ 22 | public class Solution { 23 | public TreeNode sortedListToBST(ListNode head) { 24 | // Start typing your Java solution below 25 | // DO NOT write main() function 26 | if(head == null){ 27 | return null; 28 | } 29 | TreeNode root = null; 30 | int len = 0; 31 | ListNode k = head; 32 | while(k!= null){ 33 | k = k.next; 34 | len++; 35 | } 36 | return build(head,len); 37 | } 38 | 39 | TreeNode build(ListNode head, int len){ 40 | if(len == 1){ 41 | TreeNode node = new TreeNode(head.val); 42 | return node; 43 | } 44 | int start = len % 2 == 0?len/2:len/2+1; 45 | ListNode mid = head; 46 | while( start > 1){ 47 | mid = mid.next; 48 | start--; 49 | } 50 | TreeNode mroot = new TreeNode(mid.val); 51 | if(mid != head){ 52 | mroot.left = build(head,len % 2 == 0 ? len/2-1 : len/2); 53 | } 54 | if(mid.next != null){ 55 | mroot.right = build(mid.next,len/2); 56 | } 57 | return mroot; 58 | } 59 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Binary Tree Inorder Traversal.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, return the inorder traversal of its nodes' values. 2 | 3 | For example: 4 | Given binary tree {1,#,2,3}, 5 | 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | return [1,3,2]. 12 | 13 | Note: Recursive solution is trivial, could you do it iteratively? 14 | 15 | 16 | ======================= 17 | iterative solution is interesting. 18 | 19 | Solutions: 20 | 21 | /** 22 | * Definition for binary tree 23 | * public class TreeNode { 24 | * int val; 25 | * TreeNode left; 26 | * TreeNode right; 27 | * TreeNode(int x) { val = x; } 28 | * } 29 | */ 30 | public class Solution { 31 | public ArrayList inorderTraversal(TreeNode root) { 32 | // Start typing your Java solution below 33 | // DO NOT write main() function 34 | ArrayList res = new ArrayList(); 35 | if(root == null){ 36 | return res; 37 | } 38 | inOrder(root,res); 39 | return res; 40 | } 41 | 42 | //iterative solution 43 | void inOrder(TreeNode node,ArrayList res){ 44 | Stack sts = new Stack(); 45 | TreeNode cur = node; 46 | while(!sts.empty() || cur != null){ 47 | if(cur != null){ 48 | sts.push(cur); 49 | cur = cur.left; 50 | }else{ 51 | cur = sts.pop(); 52 | res.add(cur.val); 53 | cur = cur.right; 54 | } 55 | } 56 | } 57 | 58 | // reccurence solution 59 | void inorder(TreeNode node,ArrayList res){ 60 | if(node == null){ 61 | return; 62 | } 63 | inorder(node.left,res); 64 | res.add(node.val); 65 | inorder(node.right,res); 66 | } 67 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Multiply Strings.txt: -------------------------------------------------------------------------------- 1 | Given two numbers represented as strings, return multiplication of the numbers as a string. 2 | 3 | Note: The numbers can be arbitrarily large and are non-negative. 4 | 5 | ======================== 6 | 7 | be careful of the 8 | 1. "","" 9 | 2. "0" case 10 | 3. multiply from tail of the two string 11 | 12 | Solution: 13 | 14 | 15 | public class Solution { 16 | public String multiply(String num1, String num2) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | List res = new ArrayList(); 20 | StringBuffer result = new StringBuffer(); 21 | if(num1.length() == 0 || num2.length() == 0){ 22 | return ""; 23 | } 24 | int add = 0; 25 | for(int i = num1.length() -1; i >= 0 ; i--){ 26 | for(int j = num2.length() -1; j>=0 ;j--){ 27 | int na = num1.charAt(i) - '0'; 28 | int nb = num2.charAt(j) - '0'; 29 | int index = (num1.length() - i) + num2.length() - j - 2; 30 | if(res.size() < index+1){ 31 | res.add(na*nb); 32 | }else{ 33 | res.set(index,res.get(index) + na*nb); 34 | } 35 | } 36 | } 37 | Stack sts = new Stack(); 38 | for(int i = 0 ; i < res.size();i++){ 39 | sts.push((res.get(i) + add ) % 10); 40 | add = (res.get(i) + add )/10; 41 | } 42 | if(add > 0){ 43 | sts.push(add); 44 | } 45 | while(!sts.empty()){ 46 | result.append(sts.pop()); 47 | } 48 | if(result.charAt(0) == '0'){ 49 | return "0"; 50 | }else{ 51 | return result.toString(); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Path Sum II.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 2 | 3 | For example: 4 | Given the below binary tree and sum = 22, 5 | 5 6 | / \ 7 | 4 8 8 | / / \ 9 | 11 13 4 10 | / \ / \ 11 | 7 2 5 1 12 | return 13 | 14 | [ 15 | [5,4,11,2], 16 | [5,8,4,5] 17 | ] 18 | 19 | ============================================= 20 | 21 | be careful of the backtraces 22 | 23 | Solution: 24 | 25 | /** 26 | * Definition for binary tree 27 | * public class TreeNode { 28 | * int val; 29 | * TreeNode left; 30 | * TreeNode right; 31 | * TreeNode(int x) { val = x; } 32 | * } 33 | */ 34 | public class Solution { 35 | public ArrayList> pathSum(TreeNode root, int sum) { 36 | // Start typing your Java solution below 37 | // DO NOT write main() function 38 | ArrayList> res = new ArrayList>(); 39 | if(root == null){ 40 | return res; 41 | } 42 | ArrayList adds = new ArrayList(); 43 | dfs(root,sum,adds,res); 44 | return res; 45 | } 46 | 47 | void dfs(TreeNode node,int sum,ArrayList adds,ArrayList> res){ 48 | if(node == null){ 49 | return ; 50 | } 51 | if(node.left == null && node.right == null && node.val == sum){ 52 | adds.add(node.val); 53 | res.add(new ArrayList(adds)); 54 | adds.remove(adds.size() -1); 55 | return; 56 | } 57 | adds.add(node.val); 58 | dfs(node.left,sum - node.val,adds,res); 59 | dfs(node.right,sum - node.val,adds,res); 60 | adds.remove(adds.size() -1); 61 | } 62 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Sum Root to Leaf Numbers.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 2 | 3 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 4 | 5 | Find the total sum of all root-to-leaf numbers. 6 | 7 | For example, 8 | 9 | 1 10 | / \ 11 | 2 3 12 | The root-to-leaf path 1->2 represents the number 12. 13 | The root-to-leaf path 1->3 represents the number 13. 14 | 15 | Return the sum = 12 + 13 = 25. 16 | 17 | ================================== 18 | 19 | 20 | 21 | be careful : if node have one subtree. we should only add this subtree to final result 22 | such as 23 | 24 | 1 25 | / 26 | 2 27 | 28 | result = 12 , not 12 + 1 29 | 30 | 31 | 32 | Solution: 33 | 34 | 35 | /** 36 | * Definition for binary tree 37 | * public class TreeNode { 38 | * int val; 39 | * TreeNode left; 40 | * TreeNode right; 41 | * TreeNode(int x) { val = x; } 42 | * } 43 | */ 44 | public class Solution { 45 | class sum{ 46 | int res = 0; 47 | } 48 | public int sumNumbers(TreeNode root) { 49 | // Start typing your Java solution below 50 | // DO NOT write main() function 51 | sum res = new sum(); 52 | dfs(root,0,res); 53 | return res.res; 54 | } 55 | 56 | void dfs(TreeNode node,int last,sum res){ 57 | if(node == null){ 58 | res.res += last; 59 | return; 60 | } 61 | if(node.left == null && node.right == null){ 62 | res.res += last * 10 + node.val; 63 | return; 64 | } 65 | if(node.left != null){ 66 | dfs(node.left,last*10 + node.val,res); 67 | } 68 | if(node.right != null){ 69 | dfs(node.right,last * 10+node.val,res); 70 | } 71 | 72 | } 73 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Flatten Binary Tree to Linked List.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, flatten it to a linked list in-place. 2 | 3 | For example, 4 | Given 5 | 6 | 1 7 | / \ 8 | 2 5 9 | / \ \ 10 | 3 4 6 11 | The flattened tree should look like: 12 | 1 13 | \ 14 | 2 15 | \ 16 | 3 17 | \ 18 | 4 19 | \ 20 | 5 21 | \ 22 | 6 23 | Hints: 24 | If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. 25 | 26 | 27 | =============================================================== 28 | 29 | 30 | Solution: 31 | /** 32 | * Definition for binary tree 33 | * public class TreeNode { 34 | * int val; 35 | * TreeNode left; 36 | * TreeNode right; 37 | * TreeNode(int x) { val = x; } 38 | * } 39 | */ 40 | public class Solution { 41 | public void flatten(TreeNode root) { 42 | // Start typing your Java solution below 43 | // DO NOT write main() function 44 | if(root == null){ 45 | return; 46 | } 47 | Stack sts = new Stack(); 48 | sts.push(root); 49 | TreeNode head = null; 50 | TreeNode tail = null; 51 | while(!sts.empty()){ 52 | TreeNode node = sts.pop(); 53 | if(head == null){ 54 | head = node; 55 | tail = node; 56 | }else{ 57 | tail.right = node; 58 | tail.left = null; 59 | tail = tail.right; 60 | } 61 | if(node.right != null){ 62 | sts.push(node.right); 63 | } 64 | if(node.left != null){ 65 | sts.push(node.left); 66 | } 67 | } 68 | root = head; 69 | } 70 | 71 | 72 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Regular Expression Matching.txt: -------------------------------------------------------------------------------- 1 | Implement regular expression matching with support for '.' and '*'. 2 | 3 | '.' Matches any single character. 4 | '*' Matches zero or more of the preceding element. 5 | 6 | The matching should cover the entire input string (not partial). 7 | 8 | The function prototype should be: 9 | bool isMatch(const char *s, const char *p) 10 | 11 | Some examples: 12 | isMatch("aa","a") ? false 13 | isMatch("aa","aa") ? true 14 | isMatch("aaa","aa") ? false 15 | isMatch("aa", "a*") ? true 16 | isMatch("aa", ".*") ? true 17 | isMatch("ab", ".*") ? true 18 | isMatch("aab", "c*a*b") ? true 19 | 20 | 21 | =========================================================== 22 | 23 | take care of the terminal conditions. 24 | there are some rules to optimize the recurrence 25 | 26 | Solution: 27 | 28 | public class Solution { 29 | public boolean isMatch(String s, String p) { 30 | // Start typing your Java solution below 31 | // DO NOT write main() function 32 | if(s == null){return p == null;} 33 | return match(s,0,p,0); 34 | } 35 | 36 | boolean match(String s,int is, String p,int ip){ 37 | if(ip == p.length()){return is == s.length();} 38 | if(ip == p.length() -1 || p.charAt(ip + 1) != '*'){ 39 | if(is == s.length()){return false;} 40 | return (p.charAt(ip) == s.charAt(is) || p.charAt(ip) == '.') && match(s,is+1,p,ip+1); 41 | } 42 | // important rule to optimize the recurrence 43 | // for a* and aaaa , first match i + 2 and j++, if not match than j++, when j != i return i + 2 , j 44 | // reduce much calculations 45 | while(is < s.length() && (p.charAt(ip) == '.' || p.charAt(ip) == s.charAt(is))){ 46 | if(match(s,is++,p,ip+2)){ 47 | return true; 48 | } 49 | } 50 | return match(s,is,p,ip+2); 51 | } 52 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Binary Tree Level Order Traversal.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 2 | 3 | For example: 4 | Given binary tree {3,9,20,#,#,15,7}, 5 | 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its level order traversal as: 12 | 13 | [ 14 | [3], 15 | [9,20], 16 | [15,7] 17 | ] 18 | 19 | =============================== 20 | 21 | Solution: 22 | 23 | /** 24 | * Definition for binary tree 25 | * public class TreeNode { 26 | * int val; 27 | * TreeNode left; 28 | * TreeNode right; 29 | * TreeNode(int x) { val = x; } 30 | * } 31 | */ 32 | public class Solution { 33 | public ArrayList> levelOrder(TreeNode root) { 34 | // Start typing your Java solution below 35 | // DO NOT write main() function 36 | ArrayList> res = new ArrayList>(); 37 | if(root == null){ 38 | return res; 39 | } 40 | Queue ques = new LinkedList(); 41 | ques.add(root); 42 | int cnum = 1; 43 | int nnum = 0; 44 | List adds = new ArrayList(); 45 | while(!ques.isEmpty()){ 46 | TreeNode node = ques.poll(); 47 | adds.add(node.val); 48 | cnum--; 49 | if(node.left != null){ 50 | ques.add(node.left); 51 | nnum++; 52 | } 53 | if(node.right != null){ 54 | ques.add(node.right); 55 | nnum++; 56 | } 57 | if(cnum == 0){ 58 | cnum = nnum; 59 | nnum = 0; 60 | res.add(new ArrayList(adds)); 61 | adds.clear(); 62 | } 63 | } 64 | return res; 65 | } 66 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Combination Sum II.txt: -------------------------------------------------------------------------------- 1 | Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 2 | 3 | Each number in C may only be used once in the combination. 4 | 5 | Note: 6 | 7 | All numbers (including target) will be positive integers. 8 | Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 ? a2 ? ... ? ak). 9 | The solution set must not contain duplicate combinations. 10 | For example, given candidate set 10,1,2,7,6,1,5 and target 8, 11 | A solution set is: 12 | [1, 7] 13 | [1, 2, 5] 14 | [2, 6] 15 | [1, 1, 6] 16 | 17 | 18 | ================================ 19 | 20 | 21 | 22 | Solution: 23 | 24 | public class Solution { 25 | public ArrayList> combinationSum2(int[] num, int target) { 26 | // Start typing your Java solution below 27 | // DO NOT write main() function 28 | ArrayList> res = new ArrayList>(); 29 | if(num.length == 0){ 30 | return res; 31 | } 32 | Arrays.sort(num); 33 | ArrayList adds = new ArrayList(); 34 | dfs(num,0,target,adds,res); 35 | return res; 36 | } 37 | 38 | void dfs(int[] num, int index, int target,ArrayList adds,ArrayList> res){ 39 | if(target == 0){ 40 | res.add(new ArrayList(adds)); 41 | return ; 42 | } 43 | HashSet checks = new HashSet(); 44 | for(int i = index; i< num.length; i++){ 45 | if(target >= num[i] && !checks.contains(num[i])){ 46 | checks.add(num[i]); 47 | adds.add(num[i]); 48 | dfs(num,i+1,target - num[i],adds,res); 49 | adds.remove(adds.size() -1); 50 | } 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Partition List.txt: -------------------------------------------------------------------------------- 1 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 2 | 3 | You should preserve the original relative order of the nodes in each of the two partitions. 4 | 5 | For example, 6 | Given 1->4->3->2->5->2 and x = 3, 7 | return 1->2->2->4->3->5. 8 | 9 | ====================== 10 | 11 | two pointer 12 | 13 | Solution: 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * public class ListNode { 18 | * int val; 19 | * ListNode next; 20 | * ListNode(int x) { 21 | * val = x; 22 | * next = null; 23 | * } 24 | * } 25 | */ 26 | public class Solution { 27 | public ListNode partition(ListNode head, int x) { 28 | // Start typing your Java solution below 29 | // DO NOT write main() function 30 | ListNode big = null; 31 | ListNode btail = null; 32 | ListNode small = null; 33 | ListNode stail = null; 34 | ListNode k = head; 35 | while(k != null){ 36 | if(k.val < x){ 37 | if(small == null){ 38 | small = k; 39 | stail = k; 40 | }else{ 41 | stail.next = k; 42 | stail = stail.next; 43 | } 44 | }else{ 45 | if(big == null){ 46 | big = k; 47 | btail = k; 48 | }else{ 49 | btail.next = k; 50 | btail = btail.next; 51 | } 52 | } 53 | k = k.next; 54 | } 55 | if(btail != null){ 56 | btail.next = null; 57 | } 58 | if(stail != null){ 59 | stail.next = big; 60 | return small; 61 | }else{ 62 | return big; 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Unique Paths II.txt: -------------------------------------------------------------------------------- 1 | Follow up for "Unique Paths": 2 | 3 | Now consider if some obstacles are added to the grids. How many unique paths would there be? 4 | 5 | An obstacle and empty space is marked as 1 and 0 respectively in the grid. 6 | 7 | For example, 8 | 9 | There is one obstacle in the middle of a 3x3 grid as illustrated below. 10 | 11 | [ 12 | [0,0,0], 13 | [0,1,0], 14 | [0,0,0] 15 | ] 16 | The total number of unique paths is 2. 17 | 18 | Note: m and n will be at most 100. 19 | 20 | ============================================ 21 | 22 | can't use one array to record the result. 23 | in the initialization, for first row and first column, if meet one 1, rest will be 0. 24 | 25 | Solution: 26 | 27 | public class Solution { 28 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 29 | // Start typing your Java solution below 30 | // DO NOT write main() function 31 | if(obstacleGrid.length == 0 || obstacleGrid[0].length == 0){ 32 | return 0; 33 | } 34 | int n = obstacleGrid.length; 35 | int m = obstacleGrid[0].length; 36 | int[][] res = new int[n][m]; 37 | for(int i = 0 ; i < m ; i++){ 38 | if(obstacleGrid[0][i] == 0){ 39 | res[0][i] = 1; 40 | }else{ 41 | break; 42 | } 43 | } 44 | for(int i = 0 ; i < n; i++){ 45 | if(obstacleGrid[i][0] == 0){ 46 | res[i][0] = 1; 47 | }else{ 48 | break; 49 | } 50 | } 51 | for(int i = 1 ; i < n;i++){ 52 | for(int j = 1; j < m; j++){ 53 | if(obstacleGrid[i][j] == 1){ 54 | res[i][j] = 0; 55 | }else{ 56 | res[i][j] = res[i][j-1] + res[i-1][j]; 57 | } 58 | } 59 | } 60 | return res[n-1][m-1]; 61 | } 62 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Search in Rotated Sorted Array II.txt: -------------------------------------------------------------------------------- 1 | 2 | Follow up for "Search in Rotated Sorted Array": 3 | What if duplicates are allowed? 4 | 5 | Would this affect the run-time complexity? How and why? 6 | 7 | Write a function to determine if a given target is in the array. 8 | 9 | ========================================================================== 10 | 11 | 12 | Solution: 13 | 14 | public class Solution { 15 | public boolean search(int[] A, int target) { 16 | // Start typing your Java solution below 17 | // DO NOT write main() function 18 | if(A == null || A.length == 0){ 19 | return false; 20 | } 21 | int low = 0; 22 | int high = A.length -1; 23 | while(low < high){ 24 | if(A[low] == target){return true;} 25 | if(A[high] == target){return true;} 26 | int mid = low + (high - low) / 2; 27 | if(A[mid] == target){ 28 | return true; 29 | } 30 | if(A[high] == A[low]){ 31 | high--; 32 | }else if(A[high] > A[low]){ 33 | if(A[mid] > target){ 34 | high = mid -1; 35 | }else{ 36 | low = mid+1; 37 | } 38 | }else{ 39 | if(A[mid] > target){ 40 | if(target < A[high] && A[mid] > A[high]){ 41 | low = mid + 1; 42 | }else{ 43 | high = mid -1; 44 | } 45 | }else{ 46 | if(target > A[high] && A[mid] < A[high]){ 47 | high = mid -1; 48 | }else{ 49 | low = mid + 1; 50 | } 51 | } 52 | } 53 | } 54 | if(A[low] == target){ 55 | return true; 56 | }else{ 57 | return false; 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Word Search.txt: -------------------------------------------------------------------------------- 1 | Given a 2D board and a word, find if the word exists in the grid. 2 | 3 | The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. 4 | 5 | For example, 6 | Given board = 7 | 8 | [ 9 | ["ABCE"], 10 | ["SFCS"], 11 | ["ADEE"] 12 | ] 13 | word = "ABCCED", -> returns true, 14 | word = "SEE", -> returns true, 15 | word = "ABCB", -> returns false. 16 | 17 | ================================== 18 | 19 | use a hashset to record the visited postion 20 | 21 | Solution: 22 | 23 | public class Solution { 24 | public boolean exist(char[][] board, String word) { 25 | // Start typing your Java solution below 26 | // DO NOT write main() function 27 | if(board == null || board.length == 0){ 28 | return false; 29 | } 30 | for(int i = 0 ; i < board.length; i++){ 31 | for(int j = 0 ; j < board[0].length; j++){ 32 | HashSet visited = new HashSet(); 33 | if(dfs(board,word,0,i,j,visited)){return true;} 34 | } 35 | } 36 | return false; 37 | } 38 | 39 | boolean dfs(char[][] board,String word,int len,int i , int j,HashSet visited){ 40 | if(len == word.length()){return true;} 41 | if(i < 0 || i >= board.length || j < 0 || j >= board[0].length){ 42 | return false; 43 | } 44 | if(board[i][j] != word.charAt(len) || visited.contains(i * board[0].length + j)){ 45 | return false; 46 | }else { 47 | visited.add(i * board[0].length + j); 48 | //search left 49 | return dfs(board,word,len+1,i-1,j,visited) || 50 | dfs(board,word,len+1,i,j-1,visited) || 51 | dfs(board,word,len+1,i+1,j,visited)|| 52 | dfs(board,word,len+1,i,j+1,visited); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Merge Intervals.txt: -------------------------------------------------------------------------------- 1 | Given a collection of intervals, merge all overlapping intervals. 2 | 3 | For example, 4 | Given [1,3],[2,6],[8,10],[15,18], 5 | return [1,6],[8,10],[15,18]. 6 | 7 | 8 | 9 | ========================================================= 10 | 11 | Complexity: O(nlogn) 12 | 13 | please take care that next interval maybe contains in the previous one 14 | [6,15], [8,13] 15 | 16 | Solution: 17 | 18 | /** 19 | * Definition for an interval. 20 | * public class Interval { 21 | * int start; 22 | * int end; 23 | * Interval() { start = 0; end = 0; } 24 | * Interval(int s, int e) { start = s; end = e; } 25 | * } 26 | */ 27 | public class Solution { 28 | 29 | class comparetor implements Comparator{ 30 | @Override 31 | public int compare(Interval o1,Interval o2){ 32 | if(o1.start > o2.start){ 33 | return 1; 34 | }else if(o1.start == o2.start){ 35 | return 0; 36 | }else{ 37 | return -1; 38 | } 39 | } 40 | } 41 | 42 | public ArrayList merge(ArrayList intervals) { 43 | // Start typing your Java solution below 44 | // DO NOT write main() function 45 | ArrayList res = new ArrayList(); 46 | if(intervals.size() == 0){ 47 | return res; 48 | } 49 | Collections.sort(intervals,new comparetor()); 50 | int start = intervals.get(0).start; 51 | int end = intervals.get(0).end; 52 | for(int i = 0 ; i < intervals.size();i++){ 53 | if(intervals.get(i).start <= end){ 54 | end = Math.max(end,intervals.get(i).end); 55 | }else{ 56 | res.add(new Interval(start,end)); 57 | start = intervals.get(i).start; 58 | end = intervals.get(i).end; 59 | } 60 | } 61 | res.add(new Interval(start,end)); 62 | return res; 63 | } 64 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Combination Sum.txt: -------------------------------------------------------------------------------- 1 | Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 2 | 3 | The same repeated number may be chosen from C unlimited number of times. 4 | 5 | Note: 6 | 7 | All numbers (including target) will be positive integers. 8 | Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 ? a2 ? .. ? ak). 9 | The solution set must not contain duplicate combinations. 10 | For example, given candidate set 2,3,6,7 and target 7, 11 | A solution set is: 12 | [7] 13 | [2, 2, 3] 14 | 15 | =================================== 16 | 17 | 1. sort the array 18 | 2. be careful of the index of current recurrence. 19 | 3. avoid same key in same recurrence 20 | 21 | Solution: 22 | 23 | public class Solution { 24 | public ArrayList> combinationSum(int[] candidates, int target) { 25 | // Start typing your Java solution below 26 | // DO NOT write main() function 27 | ArrayList> res = new ArrayList>(); 28 | if(candidates.length == 0){ 29 | return res; 30 | } 31 | Arrays.sort(candidates); 32 | ArrayList adds = new ArrayList(); 33 | dfs(candidates,0,target,adds,res); 34 | return res; 35 | } 36 | 37 | void dfs(int[] nums, int index,int target, ArrayList adds,ArrayList> res){ 38 | if(target == 0 ){ 39 | res.add(new ArrayList(adds)); 40 | return; 41 | } 42 | HashSet checks = new HashSet(); 43 | for(int i = index ; i < nums.length; i++){ 44 | if(target >= nums[i] && !checks.contains(nums[i])){ 45 | adds.add(nums[i]); 46 | dfs(nums,i,target-nums[i],adds,res); 47 | checks.add(nums[i]); 48 | adds.remove(adds.size() -1); 49 | } 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Merge k Sorted Lists.txt: -------------------------------------------------------------------------------- 1 | Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 2 | 3 | ===================== 4 | 5 | Complexity O(mn) 6 | 7 | take care of the repeated iterms 8 | 9 | Solution: 10 | 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * public class ListNode { 15 | * int val; 16 | * ListNode next; 17 | * ListNode(int x) { 18 | * val = x; 19 | * next = null; 20 | * } 21 | * } 22 | */ 23 | public class Solution { 24 | public ListNode mergeKLists(ArrayList lists) { 25 | // Start typing your Java solution below 26 | // DO NOT write main() function 27 | 28 | ListNode head = null; 29 | ListNode tail = null; 30 | int finish = 0; 31 | while(finish < lists.size()){ 32 | finish = 0; 33 | ListNode min = null; 34 | for(int i = 0 ; i < lists.size(); i++){ 35 | if(lists.get(i) == null){ 36 | finish++; 37 | }else{ 38 | if(min == null) 39 | { 40 | min = lists.get(i); 41 | }else if(min.val > lists.get(i).val){ 42 | min = lists.get(i); 43 | } 44 | } 45 | } 46 | if(finish == lists.size()){break;} 47 | for(int i = 0 ; i < lists.size();i++){ 48 | if(lists.get(i) == null){continue;} 49 | while(lists.get(i) != null && lists.get(i).val == min.val){ 50 | if(head == null){ 51 | head = lists.get(i);tail = lists.get(i); 52 | }else{ 53 | tail.next = lists.get(i); 54 | tail = tail.next; 55 | } 56 | lists.set(i,lists.get(i).next); 57 | } 58 | } 59 | } 60 | return head; 61 | } 62 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Wildcard Matching.txt: -------------------------------------------------------------------------------- 1 | Implement wildcard pattern matching with support for '?' and '*'. 2 | 3 | '?' Matches any single character. 4 | '*' Matches any sequence of characters (including the empty sequence). 5 | 6 | The matching should cover the entire input string (not partial). 7 | 8 | The function prototype should be: 9 | bool isMatch(const char *s, const char *p) 10 | 11 | Some examples: 12 | isMatch("aa","a") ? false 13 | isMatch("aa","aa") ? true 14 | isMatch("aaa","aa") ? false 15 | isMatch("aa", "*") ? true 16 | isMatch("aa", "a*") ? true 17 | isMatch("ab", "?*") ? true 18 | isMatch("aab", "c*a*b") ? false 19 | 20 | =============================================== 21 | 22 | use iterator to solve the problem 23 | take care the case "aa" "*" and "c","*?*" 24 | corresponding with that two case, 25 | when j == '*' j ++; i don't change 26 | 27 | 28 | Solution: 29 | 30 | public class Solution { 31 | public boolean isMatch(String s, String p) { 32 | // Start typing your Java solution below 33 | // DO NOT write main() function 34 | if(s == null){return p == null;} 35 | return match(s,p); 36 | } 37 | boolean match(String s, String p){ 38 | 39 | int is = 0 ; 40 | int ip = 0 ; 41 | int markp = -1; 42 | int marks = -1; 43 | while(is < s.length()){ 44 | if(ip != p.length() && p.charAt(ip) == '*'){ 45 | markp = ip; 46 | marks = is; 47 | ip++; 48 | }else{ 49 | if(ip != p.length() && (p.charAt(ip) == '?' || s.charAt(is) == p.charAt(ip))) 50 | { 51 | ip++;is++; 52 | }else if(markp >= 0){ 53 | ip = markp + 1; 54 | is = ++marks; 55 | }else{ 56 | return false; 57 | } 58 | } 59 | } 60 | while(ip < p.length() && p.charAt(ip) == '*'){ip++;} 61 | return is == s.length() && ip == p.length(); 62 | } 63 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Insert Interval.txt: -------------------------------------------------------------------------------- 1 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 2 | 3 | You may assume that the intervals were initially sorted according to their start times. 4 | 5 | Example 1: 6 | Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. 7 | 8 | Example 2: 9 | Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. 10 | 11 | This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. 12 | 13 | ========================================================= 14 | 15 | Complexity: O(n) 16 | 17 | it has three situations: 18 | 19 | current interval before newInterval; 20 | newInterval before current interval 21 | they have overlap 22 | 23 | 24 | 25 | Solution: 26 | 27 | /** 28 | * Definition for an interval. 29 | * public class Interval { 30 | * int start; 31 | * int end; 32 | * Interval() { start = 0; end = 0; } 33 | * Interval(int s, int e) { start = s; end = e; } 34 | * } 35 | */ 36 | public class Solution { 37 | public ArrayList insert(ArrayList intervals, Interval newInterval) { 38 | // Start typing your Java solution below 39 | // DO NOT write main() function 40 | ArrayList res = new ArrayList(); 41 | if(intervals.size() == 0){ 42 | res.add(newInterval); 43 | return res; 44 | } 45 | 46 | for(int i = 0 ; i < intervals.size(); i++){ 47 | if(intervals.get(i).start > newInterval.end){ 48 | res.add(newInterval); 49 | newInterval = intervals.get(i); 50 | }else if(intervals.get(i).end < newInterval.start){ 51 | res.add(intervals.get(i)); 52 | }else{ 53 | newInterval.start = Math.min(newInterval.start,intervals.get(i).start); 54 | newInterval.end = Math.max(newInterval.end,intervals.get(i).end); 55 | } 56 | } 57 | res.add(newInterval); 58 | return res; 59 | } 60 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Generate Parentheses.txt: -------------------------------------------------------------------------------- 1 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 2 | 3 | For example, given n = 3, a solution set is: 4 | 5 | "((()))", "(()())", "(())()", "()(())", "()()()" 6 | 7 | ============================= 8 | 9 | Complexity 10 | 11 | DFS, but take care that repeated cases 12 | 13 | Solution: 14 | 15 | public class Solution { 16 | public ArrayList generateParenthesis(int n) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | ArrayList res = new ArrayList(); 20 | if(n == 0 ){ 21 | return res; 22 | } 23 | char[] ins = new char[2 * n]; 24 | for(int i = 0 ; i < ins.length; i++){ 25 | ins[i++] = '('; 26 | ins[i] = ')'; 27 | } 28 | dfs(ins,0,"",res); 29 | return res; 30 | } 31 | 32 | void dfs(char[] ins,int start,String add,ArrayList res){ 33 | if(start == ins.length){ 34 | if(valid(add)){res.add(add);} 35 | return; 36 | } 37 | Set checks = new HashSet(); 38 | for(int i = start ; i < ins.length ; i++){ 39 | if(checks.contains(ins[i])){continue;} 40 | checks.add(ins[i]); 41 | swap(ins,start,i); 42 | dfs(ins,start +1 , add+ins[start],res); 43 | swap(ins,start,i); 44 | } 45 | } 46 | 47 | void swap(char[] ins,int ia,int ib){ 48 | char tmp = ins[ia]; 49 | ins[ia] = ins[ib]; 50 | ins[ib] = tmp; 51 | } 52 | 53 | boolean valid(String input){ 54 | Stack sts = new Stack(); 55 | for(int i = 0 ; i < input.length(); i++){ 56 | if(input.charAt(i) == ')'){ 57 | if(sts.empty() || sts.pop() != '('){return false;} 58 | }else{ 59 | sts.push('('); 60 | } 61 | } 62 | if(sts.empty()){return true;} 63 | return false; 64 | } 65 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/3Sum.txt: -------------------------------------------------------------------------------- 1 | Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 2 | 3 | Note: 4 | 5 | Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ? b ? c) 6 | The solution set must not contain duplicate triplets. 7 | 8 | For example, given array S = {-1 0 1 2 -1 -4}, 9 | 10 | A solution set is: 11 | (-1, 0, 1) 12 | (-1, -1, 2) 13 | 14 | ======================================================================= 15 | 16 | Complexity : O(n^2) 17 | 18 | please remember how to avoid the replicate cases 19 | 1. in the first loop 20 | 2. int the while 21 | Solution: 22 | 23 | public class Solution { 24 | public ArrayList> threeSum(int[] num) { 25 | // Start typing your Java solution below 26 | // DO NOT write main() function 27 | ArrayList> res = new ArrayList>(); 28 | if(num == null || num.length == 0){ 29 | return res; 30 | } 31 | Arrays.sort(num); 32 | for(int i = 0 ; i < num.length - 2; i++){ 33 | if(i != 0 && num[i] == num[i-1] ){ 34 | continue; 35 | } 36 | int left = i + 1; 37 | int right = num.length -1; 38 | while(left < right){ 39 | if(num[left] + num[right] == 0 - num[i]){ 40 | ArrayList adds = new ArrayList(); 41 | adds.add(num[i]);adds.add(num[left]);adds.add(num[right]); 42 | res.add(adds); 43 | int tmpl = num[left++]; 44 | int tmpr = num[right--]; 45 | while( left <= right && tmpl == num[left] && tmpr == num[right]){left++;right--;} 46 | }else if(num[left] + num[right] > 0 - num[i]){ 47 | right--; 48 | }else{ 49 | left++; 50 | } 51 | } 52 | } 53 | return res; 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /leetCode/Leetcode/Letter Combinations of a Phone Number.txt: -------------------------------------------------------------------------------- 1 | Given a digit string, return all possible letter combinations that the number could represent. 2 | 3 | A mapping of digit to letters (just like on the telephone buttons) is given below. 4 | Input:Digit string "23" 5 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 6 | 7 | =========================== 8 | 9 | when input is "" output should be "" too. 10 | 11 | Solutions: 12 | 13 | public class Solution { 14 | public ArrayList letterCombinations(String digits) { 15 | // Start typing your Java solution below 16 | // DO NOT write main() function 17 | ArrayList res = new ArrayList(); 18 | if(digits.length() == 0){ 19 | res.add(""); 20 | return res; 21 | } 22 | String[] words = new String[]{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 23 | //dfs(digits,0,words,"",res); 24 | res = iterative(digits,words); 25 | return res; 26 | } 27 | 28 | //a reccrurence solution 29 | void dfs(String digits, int index,String[] words, String add, ArrayList res){ 30 | if(index == digits.length()){ 31 | res.add(add); 32 | return; 33 | } 34 | String word = words[digits.charAt(index) - '2']; 35 | for(int i = 0 ; i < word.length(); i++){ 36 | dfs(digits,index+1,words,add+word.charAt(i),res); 37 | } 38 | } 39 | 40 | // an iterative solution 41 | ArrayList iterative(String digits, String[] words){ 42 | ArrayList res = new ArrayList(); 43 | res.add(""); 44 | for(int i = 0; i < digits.length() ;i ++){ 45 | String word = words[digits.charAt(i) - '2']; 46 | ArrayList tmps = new ArrayList(); 47 | for(int j = 0 ; j < word.length(); j ++){ 48 | for(String re : res){ 49 | tmps.add(re + word.charAt(j)); 50 | } 51 | } 52 | res = tmps; 53 | } 54 | return res; 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Merge Two Sorted Lists.txt: -------------------------------------------------------------------------------- 1 | 2 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 3 | 4 | ========================================= 5 | 6 | Complexity space O(1) time O(m+n) 7 | 8 | take care l1 maybe null and l2 maybe null 9 | 10 | Solution: 11 | /** 12 | * Definition for singly-linked list. 13 | * public class ListNode { 14 | * int val; 15 | * ListNode next; 16 | * ListNode(int x) { 17 | * val = x; 18 | * next = null; 19 | * } 20 | * } 21 | */ 22 | public class Solution { 23 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 24 | // Start typing your Java solution below 25 | // DO NOT write main() function 26 | if(l1 == null || l2 == null){ 27 | return l2 == null ? l1:l2; 28 | } 29 | ListNode head = null; 30 | ListNode tail = null; 31 | 32 | while(l1 != null || l2 != null){ 33 | if(l1 != null && l2 != null){ 34 | if(l1.val <= l2.val){ 35 | if(head == null){ 36 | head = l1; 37 | tail = l1; 38 | }else{ 39 | tail.next = l1; 40 | tail = tail.next; 41 | } 42 | l1 = l1.next; 43 | }else{ 44 | if(head == null){ 45 | head = l2; 46 | tail = l2; 47 | }else{ 48 | tail.next = l2; 49 | tail = tail.next; 50 | } 51 | l2 = l2.next; 52 | } 53 | }else if(l1 == null && l2 != null){ 54 | tail.next = l2; 55 | tail = tail.next; 56 | l2 = l2.next; 57 | }else if(l1 != null && l2 == null){ 58 | tail.next = l1; 59 | tail = tail.next; 60 | l1 = l1.next; 61 | } 62 | } 63 | return head; 64 | } 65 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Restore IP Addresses.txt: -------------------------------------------------------------------------------- 1 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 2 | 3 | For example: 4 | Given "25525511135", 5 | 6 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 7 | 8 | =============== 9 | 10 | be careful that, when size < 0 should return; 11 | 12 | Solution: 13 | 14 | public class Solution { 15 | public ArrayList restoreIpAddresses(String s) { 16 | // Start typing your Java solution below 17 | // DO NOT write main() function 18 | ArrayList res = new ArrayList(); 19 | if(s.length() <= 3){ 20 | return res; 21 | } 22 | dfs(s,0,4,new StringBuffer(),res); 23 | return res; 24 | } 25 | 26 | void dfs(String s, int index , int size,StringBuffer add, ArrayList res){ 27 | if(index == s.length()&& size == 0){ 28 | res.add(add.toString()); 29 | return; 30 | } 31 | for(int i = index + 1; i <= s.length() && i - index < 4;i++){ 32 | String ns = s.substring(index,i); 33 | if(valid(ns) && size > 0){ 34 | StringBuffer tmp =new StringBuffer(add); 35 | if(tmp.length() == 0){ 36 | tmp.append(ns); 37 | }else{ 38 | tmp.append("." + ns); 39 | } 40 | dfs(s,i,size-1,tmp,res); 41 | } 42 | } 43 | } 44 | 45 | boolean valid(String s){ 46 | if( s.length() > 3 || (s.length() == 2 && s.charAt(0) == '0')){ 47 | return false; 48 | }else if(s.length() == 3){ 49 | if(s.charAt(0) == '0' || s.charAt(0) >='3'){ 50 | return false; 51 | } 52 | if(s.charAt(0) == '2'){ 53 | int tmp = (s.charAt(0) - '0' ) * 100 + (s.charAt(1) - '0') * 10 + s.charAt(2) - '0'; 54 | if(tmp > 255){ 55 | return false; 56 | } 57 | } 58 | return true; 59 | }else{ 60 | return true; 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Recover Binary Search Tree.txt: -------------------------------------------------------------------------------- 1 | Two elements of a binary search tree (BST) are swapped by mistake. 2 | 3 | Recover the tree without changing its structure. 4 | 5 | Note: 6 | A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 7 | 8 | ================================================== 9 | 10 | solution 1: get it's inorder traversal and find the two faulty positions 11 | solution 2: use in order traversal and record two faulty positions, without o(n) space 12 | for solution 2. use pointer pre to record the pre node 13 | 14 | for case : 6 8 14 , one condition is 14 8 6 , another is 8 6 14, we don't know which two are the faulty positions 15 | so we record first to 14/8 next to 8/6 and go on, if there is no faulty positions, it is done, or we will update next pointer to 14 16 | the judgement is pre.val > now.val 17 | 18 | Solution: 19 | 20 | /** 21 | * Definition for binary tree 22 | * public class TreeNode { 23 | * int val; 24 | * TreeNode left; 25 | * TreeNode right; 26 | * TreeNode(int x) { val = x; } 27 | * } 28 | */ 29 | public class Solution { 30 | class res { 31 | TreeNode first = null; 32 | TreeNode second = null; 33 | TreeNode pre = null; 34 | } 35 | 36 | public void recoverTree(TreeNode root) { 37 | // Start typing your Java solution below 38 | // DO NOT write main() function 39 | res res = new res(); 40 | find(root,res); 41 | if(res.first != null && res.second != null){ 42 | int tmp = res.first.val; 43 | res.first.val = res.second.val; 44 | res.second.val = tmp; 45 | } 46 | return; 47 | } 48 | 49 | void find(TreeNode node, res res){ 50 | if(node == null){ 51 | return; 52 | } 53 | find(node.left,res); 54 | if(res.pre != null && res.pre.val > node.val){ 55 | res.second = node; 56 | if(res.first == null){ 57 | res.first = res.pre; 58 | } 59 | } 60 | res.pre = node; 61 | find(node.right,res); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /leetCode/Leetcode/Validate Binary Search Tree.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, determine if it is a valid binary search tree (BST). 2 | 3 | Assume a BST is defined as follows: 4 | 5 | The left subtree of a node contains only nodes with keys less than the node's key. 6 | The right subtree of a node contains only nodes with keys greater than the node's key. 7 | Both the left and right subtrees must also be binary search trees. 8 | 9 | 10 | Complexity: O(n) 11 | 12 | 1. use upper and lower to traverse the tree. 13 | 2. get in-order traverse and check whether it is in asc order 14 | 15 | Solutions: 16 | 17 | /** 18 | * Definition for binary tree 19 | * public class TreeNode { 20 | * int val; 21 | * TreeNode left; 22 | * TreeNode right; 23 | * TreeNode(int x) { val = x; } 24 | * } 25 | */ 26 | public class Solution { 27 | public boolean isValidBST(TreeNode root) { 28 | // Start typing your Java solution below 29 | // DO NOT write main() function 30 | return solve(root,null,null); 31 | } 32 | 33 | // only one traverse 34 | boolean solve(TreeNode node, Integer lower, Integer uper){ 35 | if(node == null){ 36 | return true; 37 | } 38 | if(lower != null && node.val <= lower){ 39 | return false; 40 | } 41 | if(uper != null && node.val >= uper){ 42 | return false; 43 | } 44 | return solve(node.left,lower,node.val) && solve(node.right,node.val,uper); 45 | } 46 | 47 | 48 | // use inorder 49 | boolean solveWithInorder(TreeNode root){ 50 | ArrayList res = new ArrayList(); 51 | inorder(root,res); 52 | for(int i = 0 ; i < res.size();i ++){ 53 | if(i != 0 && res.get(i ) <= res.get(i -1)){ 54 | return false; 55 | } 56 | } 57 | return true; 58 | } 59 | 60 | void inorder(TreeNode node,ArrayList res){ 61 | if(node == null){ 62 | return; 63 | } 64 | inorder(node.left,res); 65 | res.add(node.val); 66 | inorder(node.right,res); 67 | } 68 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Follow up for problem Populating Next Right Pointers in Each Node..txt: -------------------------------------------------------------------------------- 1 | Follow up for problem "Populating Next Right Pointers in Each Node". 2 | 3 | What if the given tree could be any binary tree? Would your previous solution still work? 4 | 5 | Note: 6 | 7 | You may only use constant extra space. 8 | For example, 9 | Given the following binary tree, 10 | 11 | 1 12 | / \ 13 | 2 3 14 | / \ \ 15 | 4 5 7 16 | After calling your function, the tree should look like: 17 | 18 | 1 -> NULL 19 | / \ 20 | 2 -> 3 -> NULL 21 | / \ \ 22 | 4-> 5 -> 7 -> NULL 23 | 24 | 25 | ========================================= 26 | 27 | same as I 28 | 29 | Solution: 30 | 31 | /** 32 | * Definition for binary tree with next pointer. 33 | * public class TreeLinkNode { 34 | * int val; 35 | * TreeLinkNode left, right, next; 36 | * TreeLinkNode(int x) { val = x; } 37 | * } 38 | */ 39 | public class Solution { 40 | public void connect(TreeLinkNode root) { 41 | // Start typing your Java solution below 42 | // DO NOT write main() function 43 | if(root == null){ 44 | return; 45 | } 46 | TreeLinkNode head = null; 47 | Queue ques = new LinkedList(); 48 | int cur = 1; 49 | int next = 0; 50 | ques.add(root); 51 | while(!ques.isEmpty()){ 52 | TreeLinkNode node = ques.poll(); 53 | cur--; 54 | if(head == null){ 55 | head = node; 56 | }else{ 57 | head.next = node; 58 | head = head.next; 59 | } 60 | if(node.left != null){ 61 | ques.add(node.left); 62 | next++; 63 | } 64 | if(node.right != null){ 65 | ques.add(node.right); 66 | next++; 67 | } 68 | if(cur == 0){ 69 | cur = next; 70 | next = 0; 71 | head.next = null; 72 | head = null; 73 | } 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Search for a Range.txt: -------------------------------------------------------------------------------- 1 | Given a sorted array of integers, find the starting and ending position of a given target value. 2 | 3 | Your algorithm's runtime complexity must be in the order of O(log n). 4 | 5 | If the target is not found in the array, return [-1, -1]. 6 | 7 | For example, 8 | Given [5, 7, 7, 8, 8, 10] and target value 8, 9 | return [3, 4]. 10 | 11 | ============================= 12 | 13 | Complexity: O(logn) 14 | 15 | Solution: 16 | 17 | public class Solution { 18 | public int[] searchRange(int[] A, int target) { 19 | // Start typing your Java solution below 20 | // DO NOT write main() function 21 | int[] res = new int[2]; 22 | res[0] = -1; 23 | res[1] = -1; 24 | if(A.length == 0){ 25 | return res; 26 | } 27 | res[0] = binarySearchLeft(A,target); 28 | res[1] = binarySearchRight(A,target); 29 | return res; 30 | } 31 | 32 | int binarySearchLeft(int[] num,int target){ 33 | int low = 0; 34 | int high = num.length -1; 35 | while(low <= high){ 36 | int mid = low + (high - low) /2; 37 | if(num[mid] == target){ 38 | if(mid != 0 && num[mid - 1] == target){ 39 | high = mid -1; 40 | }else{ 41 | return mid; 42 | } 43 | }else if(num[mid] > target){ 44 | high = mid -1; 45 | }else{ 46 | low = mid + 1; 47 | } 48 | } 49 | return -1; 50 | } 51 | 52 | int binarySearchRight(int[] num,int target){ 53 | int low = 0; 54 | int high = num.length -1; 55 | while(low <= high){ 56 | int mid = low + (high - low) /2; 57 | if(num[mid] == target){ 58 | if(mid != num.length -1 && num[mid + 1] == target){ 59 | low = mid +1; 60 | }else{ 61 | return mid; 62 | } 63 | }else if(num[mid] > target){ 64 | high = mid -1; 65 | }else{ 66 | low = mid + 1; 67 | } 68 | } 69 | return -1; 70 | } 71 | 72 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Permutations.txt: -------------------------------------------------------------------------------- 1 | //recursive solution 2 | public class Solution { 3 | public ArrayList> permute(int[] num) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | ArrayList> res = new ArrayList>(); 7 | if(num == null || num.length == 0){ 8 | return res; 9 | } 10 | ArrayList adds = new ArrayList(); 11 | dfs(num,0,adds,res); 12 | return res; 13 | } 14 | void dfs(int[] num, int index, ArrayList adds,ArrayList> res){ 15 | if(index == num.length){ 16 | res.add(new ArrayList(adds)); 17 | return; 18 | } 19 | for(int i = index; i < num.length; i++){ 20 | swap(num,index,i); 21 | adds.add(num[index]); 22 | dfs(num,index+1,adds,res); 23 | swap(num,index,i); 24 | adds.remove(adds.size() -1); 25 | } 26 | } 27 | void swap(int[] num, int ia, int ib){ 28 | int tmp = num[ia]; 29 | num[ia] = num[ib]; 30 | num[ib] = tmp; 31 | } 32 | } 33 | 34 | ///iterative solution 35 | public class Solution { 36 | public ArrayList> permute(int[] num) { 37 | // Start typing your Java solution below 38 | // DO NOT write main() function 39 | ArrayList> res = new ArrayList>(); 40 | ArrayList adds = new ArrayList(); 41 | 42 | if(num.length == 0){ 43 | res.add(adds); 44 | return res; 45 | } 46 | adds.add(num[0]); 47 | res.add(adds); 48 | for(int i = 1; i < num.length; i++){ 49 | ArrayList> tres = new ArrayList>(); 50 | for(ArrayList re : res){ 51 | for(int j = 0 ; j <= re.size(); j++){ 52 | ArrayList tre = new ArrayList(re); 53 | tre.add(j,num[i]); 54 | tres.add(tre); 55 | } 56 | } 57 | res = tres; 58 | } 59 | return res; 60 | } 61 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Merge k Sorted Lists.txt: -------------------------------------------------------------------------------- 1 | Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 2 | 3 | ===================== 4 | 5 | Complexity O(mn) 6 | 7 | take care of the repeated iterms 8 | 9 | Solution: 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * public class ListNode { 14 | * int val; 15 | * ListNode next; 16 | * ListNode(int x) { 17 | * val = x; 18 | * next = null; 19 | * } 20 | * } 21 | */ 22 | public class Solution { 23 | public ListNode mergeKLists(ArrayList lists) { 24 | // Start typing your Java solution below 25 | // DO NOT write main() function 26 | if(lists.size() == 0){ 27 | return null; 28 | } 29 | int size = lists.size(); 30 | while(size > 1){ 31 | int low = 0; 32 | int high = size -1; 33 | while(low < high){ 34 | lists.set(low,mergeTwoList(lists.get(low),lists.get(high))); 35 | lists.remove(high); 36 | low ++; 37 | high--; 38 | } 39 | size = lists.size(); 40 | } 41 | return lists.get(0); 42 | } 43 | 44 | ListNode mergeTwoList(ListNode l1, ListNode l2){ 45 | ListNode head = null; 46 | ListNode tail = null; 47 | while(l1 != null || l2 != null){ 48 | ListNode tmp = null; 49 | if(l1 != null){ 50 | tmp = l1; 51 | } 52 | if(l2 != null){ 53 | if(tmp == null){ 54 | tmp = l2; 55 | l2 = l2.next; 56 | }else{ 57 | if( tmp.val > l2.val){ 58 | tmp = l2; 59 | l2 = l2.next; 60 | }else{ 61 | l1 = l1.next; 62 | } 63 | } 64 | }else{ 65 | l1 = l1.next; 66 | } 67 | if(head == null){ 68 | head = tmp; 69 | tail = tmp; 70 | }else{ 71 | tail.next = tmp; 72 | tail = tail.next; 73 | } 74 | } 75 | return head; 76 | } 77 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Word Ladder.txt: -------------------------------------------------------------------------------- 1 | Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: 2 | 3 | Only one letter can be changed at a time 4 | Each intermediate word must exist in the dictionary 5 | For example, 6 | 7 | Given: 8 | start = "hit" 9 | end = "cog" 10 | dict = ["hot","dot","dog","lot","log"] 11 | 12 | As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", 13 | return its length 5. 14 | 15 | Note: 16 | 17 | Return 0 if there is no such transformation sequence. 18 | All words have the same length. 19 | All words contain only lowercase alphabetic characters. 20 | 21 | ========================================================== 22 | 23 | Complexity: not clear 24 | 25 | use BFS to find the result, use a hashset to record the visited string 26 | 27 | Solutions: 28 | 29 | public class Solution { 30 | public int ladderLength(String start, String end, HashSet dict) { 31 | // Start typing your Java solution below 32 | // DO NOT write main() function 33 | if(start.equals(end)){ 34 | return 2; 35 | } 36 | HashSet visited = new HashSet(); 37 | Queue ques = new LinkedList(); 38 | Queue counts = new LinkedList(); 39 | ques.add(start); 40 | counts.add(1); 41 | 42 | while(ques.peek() != null){ 43 | String str = ques.poll(); 44 | int count = counts.poll(); 45 | 46 | for(int i = 0 ; i < str.length(); i++){ 47 | for(int j = 0 ; j < 26 ; j++){ 48 | if('a' + j == str.charAt(i)){continue;} 49 | char[] atts = str.toCharArray(); 50 | atts[i] = (char)('a' + j); 51 | String nstr = new String(atts); 52 | if(nstr.equals(end)){ 53 | return count+1; 54 | } 55 | if(!dict.contains(nstr) || visited.contains(nstr)){continue;} 56 | ques.add(nstr); 57 | counts.add(count + 1); 58 | visited.add(nstr); 59 | } 60 | } 61 | } 62 | return 0; 63 | } 64 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Binary Tree Zigzag Level Order Traversal.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). 2 | 3 | For example: 4 | Given binary tree {3,9,20,#,#,15,7}, 5 | 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its zigzag level order traversal as: 12 | 13 | [ 14 | [3], 15 | [20,9], 16 | [15,7] 17 | ] 18 | 19 | ========================================= 20 | 21 | Solution: 22 | 23 | 24 | /** 25 | * Definition for binary tree 26 | * public class TreeNode { 27 | * int val; 28 | * TreeNode left; 29 | * TreeNode right; 30 | * TreeNode(int x) { val = x; } 31 | * } 32 | */ 33 | public class Solution { 34 | public ArrayList> zigzagLevelOrder(TreeNode root) { 35 | // Start typing your Java solution below 36 | // DO NOT write main() function 37 | ArrayList> res = new ArrayList>(); 38 | if(root == null){ 39 | return res; 40 | } 41 | Queue que = new LinkedList(); 42 | int cur = 1; 43 | int next = 0; 44 | int level = 0; 45 | que.add(root); 46 | List adds = new ArrayList(); 47 | while(!que.isEmpty()){ 48 | TreeNode node = que.poll(); 49 | cur--; 50 | adds.add(node.val); 51 | if(node.left != null){ 52 | que.add(node.left); 53 | next++; 54 | } 55 | if(node.right != null){ 56 | que.add(node.right); 57 | next++; 58 | } 59 | if(cur == 0){ 60 | if(level % 2 == 0){ 61 | res.add(new ArrayList(adds)); 62 | }else{ 63 | ArrayList tmp = new ArrayList(); 64 | for(int i = adds.size() -1; i>= 0;i--){ 65 | tmp.add(adds.get(i)); 66 | } 67 | res.add(tmp); 68 | } 69 | adds.clear(); 70 | cur = next; 71 | next = 0; 72 | level++; 73 | } 74 | } 75 | return res; 76 | } 77 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Swap Nodes in Pairs.txt: -------------------------------------------------------------------------------- 1 | Given a linked list, swap every two adjacent nodes and return its head. 2 | 3 | For example, 4 | Given 1->2->3->4, you should return the list as 2->1->4->3. 5 | 6 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 7 | 8 | ======================================= 9 | 10 | take care: 11 | use three pointer to exchange the node postion and update the pointer 12 | 13 | 14 | Soltuion: 15 | 16 | /** 17 | * Definition for singly-linked list. 18 | * public class ListNode { 19 | * int val; 20 | * ListNode next; 21 | * ListNode(int x) { 22 | * val = x; 23 | * next = null; 24 | * } 25 | * } 26 | */ 27 | public class Solution { 28 | public ListNode swapPairs(ListNode head) { 29 | // Start typing your Java solution below 30 | // DO NOT write main() function 31 | if(head == null || head.next == null){ 32 | return head; 33 | } 34 | ListNode f = null; 35 | ListNode s = null; 36 | ListNode p = null; 37 | f = head; 38 | s = head.next; 39 | p = head; 40 | head = s; 41 | while( s != null){ 42 | f.next = s.next; 43 | s.next = f; 44 | if(p != f){ 45 | p.next = s; 46 | p = f; 47 | } 48 | f = f.next; 49 | if( f!= null){ 50 | s = f.next; 51 | }else{ 52 | break; 53 | } 54 | } 55 | return head; 56 | } 57 | } 58 | 59 | 60 | ////////////recurrence solution 61 | 62 | /** 63 | * Definition for singly-linked list. 64 | * public class ListNode { 65 | * int val; 66 | * ListNode next; 67 | * ListNode(int x) { 68 | * val = x; 69 | * next = null; 70 | * } 71 | * } 72 | */ 73 | public class Solution { 74 | public ListNode swapPairs(ListNode head) { 75 | // Start typing your Java solution below 76 | // DO NOT write main() function 77 | if(head == null || head.next == null){ 78 | return head; 79 | } 80 | ListNode pre = head; 81 | ListNode next = head.next.next; 82 | ListNode cur = head.next; 83 | cur.next = pre; 84 | pre.next = swapPairs(next); 85 | return cur; 86 | } 87 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Populating Next Right Pointers in Each Node.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree 2 | 3 | struct TreeLinkNode { 4 | TreeLinkNode *left; 5 | TreeLinkNode *right; 6 | TreeLinkNode *next; 7 | } 8 | Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. 9 | 10 | Initially, all next pointers are set to NULL. 11 | 12 | Note: 13 | 14 | You may only use constant extra space. 15 | You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). 16 | For example, 17 | Given the following perfect binary tree, 18 | 19 | 1 20 | / \ 21 | 2 3 22 | / \ / \ 23 | 4 5 6 7 24 | After calling your function, the tree should look like: 25 | 26 | 1 -> NULL 27 | / \ 28 | 2 -> 3 -> NULL 29 | / \ / \ 30 | 4->5->6->7 -> NULL 31 | 32 | ================================================ 33 | 34 | Solution: 35 | 36 | /** 37 | * Definition for binary tree with next pointer. 38 | * public class TreeLinkNode { 39 | * int val; 40 | * TreeLinkNode left, right, next; 41 | * TreeLinkNode(int x) { val = x; } 42 | * } 43 | */ 44 | public class Solution { 45 | public void connect(TreeLinkNode root) { 46 | // Start typing your Java solution below 47 | // DO NOT write main() function 48 | if(root == null){ 49 | return ; 50 | } 51 | int cur = 1; 52 | int next = 0; 53 | TreeLinkNode head = null; 54 | Queue ques = new LinkedList(); 55 | ques.add(root); 56 | while(!ques.isEmpty()){ 57 | TreeLinkNode node = ques.poll(); 58 | cur--; 59 | if(head == null){ 60 | head = node; 61 | }else{ 62 | head.next = node; 63 | head = head.next; 64 | } 65 | if(node.left != null){ 66 | ques.add(node.left); 67 | next++; 68 | } 69 | if(node.right != null){ 70 | ques.add(node.right); 71 | next++; 72 | } 73 | if(cur == 0){ 74 | cur = next; 75 | next = 0; 76 | head.next = null; 77 | head = null; 78 | } 79 | } 80 | } 81 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Decode Ways.txt: -------------------------------------------------------------------------------- 1 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 2 | 3 | 'A' -> 1 4 | 'B' -> 2 5 | ... 6 | 'Z' -> 26 7 | Given an encoded message containing digits, determine the total number of ways to decode it. 8 | 9 | For example, 10 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 11 | 12 | The number of ways decoding "12" is 2. 13 | 14 | =========================== 15 | 16 | Complexity: O(n) 17 | 18 | Solution: 19 | 20 | public class Solution { 21 | class res { 22 | int res = 0; 23 | } 24 | public int numDecodings(String s) { 25 | // Start typing your Java solution below 26 | // DO NOT write main() function 27 | if(s.length() <= 1){ 28 | return s.equals("0")?0:s.length(); 29 | } 30 | int n = s.length(); 31 | int[] res = new int[n+1]; 32 | res[0] = 1; 33 | for(int i = 1; i <= n ; i++){ 34 | int n1 = 0; 35 | if(s.charAt(i-1) != '0'){ 36 | n1 = res[i-1]; 37 | } 38 | int n2 = 0; 39 | if(i >= 2 && (s.charAt(i -2) == '1' || s.charAt(i -2) == '2' && s.charAt(i - 1) < '7')){ 40 | n2 = res[i-2]; 41 | } 42 | res[i] = n1 + n2; 43 | } 44 | return res[n]; 45 | } 46 | 47 | 48 | // can't pass large set 49 | int solveDfs(String s){ 50 | if(s.length() == 0){ 51 | return 0; 52 | } 53 | res res = new res(); 54 | dfs(s,0,res); 55 | return res.res; 56 | } 57 | 58 | void dfs(String s, int index, res res){ 59 | if(index == s.length()){ 60 | res.res++; 61 | return; 62 | } 63 | if(s.charAt(index) == '0'){ 64 | return; 65 | } 66 | if(index != s.length() -1){ 67 | if(s.charAt(index + 1) == '0'){ 68 | if(s.charAt(index) < '3'){ 69 | dfs(s,index+2,res); 70 | }else{ 71 | return; 72 | } 73 | }else if(valid(s,index)){ 74 | dfs(s,index+2,res); 75 | } 76 | } 77 | dfs(s,index+1,res); 78 | } 79 | 80 | boolean valid(String s, int index){ 81 | if(s.charAt(index) <='2' && s.charAt(index + 1) < '7'){return true;} 82 | return false; 83 | } 84 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/N-Queens.txt: -------------------------------------------------------------------------------- 1 | The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other. 2 | 3 | Given an integer n, return all distinct solutions to the n-queens puzzle. 4 | 5 | Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. 6 | 7 | For example, 8 | There exist two distinct solutions to the 4-queens puzzle: 9 | 10 | [ 11 | [".Q..", // Solution 1 12 | "...Q", 13 | "Q...", 14 | "..Q."], 15 | 16 | ["..Q.", // Solution 2 17 | "Q...", 18 | "...Q", 19 | ".Q.."] 20 | ] 21 | 22 | 23 | ================================ 24 | 25 | the point is how to check the valid status 26 | 27 | Solution: 28 | 29 | public class Solution { 30 | public ArrayList solveNQueens(int n) { 31 | // Start typing your Java solution below 32 | // DO NOT write main() function 33 | ArrayList res = new ArrayList(); 34 | if(n <= 0){ 35 | return res; 36 | } 37 | int[] queens = new int[n]; 38 | dfs(queens,0,res); 39 | return res; 40 | } 41 | 42 | void dfs(int[] queens,int index,ArrayList res){ 43 | if(index == queens.length){ 44 | res.add(print(queens)); 45 | return; 46 | } 47 | for(int i = 0; i < queens.length; i++){ 48 | queens[index] = i; 49 | if(valid(queens,index)){ 50 | dfs(queens,index+1,res); 51 | } 52 | } 53 | return; 54 | } 55 | 56 | String[] print(int[] num){ 57 | String[] res = new String[num.length]; 58 | for(int i = 0 ; i < num.length; i++){ 59 | StringBuffer row = new StringBuffer(); 60 | for(int j = 0 ; j < num.length;j++){ 61 | if(num[j] == i){ 62 | row.append("Q"); 63 | }else{ 64 | row.append("."); 65 | } 66 | } 67 | res[i] = row.toString(); 68 | } 69 | return res; 70 | } 71 | 72 | boolean valid(int[] queens,int index){ 73 | for(int i = 0 ; i < index; i++){ 74 | if(queens[i] == queens[index] || Math.abs(i - index) == Math.abs(queens[i] - queens[index])){ 75 | return false; 76 | } 77 | } 78 | return true; 79 | } 80 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Scramble String.txt: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isScramble(String s1, String s2) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if(s1.equals(s2)){ 6 | return true; 7 | }else if(s1.length() != s2.length()){ 8 | return false; 9 | } 10 | int n = s1.length(); 11 | boolean[][][] check = new boolean[n][n][n+1]; 12 | for(int i = 0 ; i < n; i++){ 13 | for(int j = 0 ; j < n ; j++){ 14 | check[i][j][0] = true; 15 | check[i][j][1] = s1.charAt(i) == s2.charAt(j); 16 | } 17 | } 18 | 19 | for(int i = n -1; i >= 0; i--){ 20 | for(int j = n - 1; j >= 0; j--){ 21 | for(int len = 2; len <= Math.min(n-i,n-j);len++){ 22 | for(int k = 1; k < len; k++){ 23 | check[i][j][len] |= (check[i][j][k] && check[i+k][j+k][len - k]) || 24 | (check[i][j+len - k][k] && check[i+ k][j][len -k]); 25 | } 26 | } 27 | } 28 | } 29 | return check[0][0][n]; 30 | } 31 | } 32 | 33 | public class Solution { 34 | public boolean isScramble(String s1, String s2) { 35 | // Start typing your Java solution below 36 | // DO NOT write main() function 37 | if(s1.length() == 1){ 38 | return s1.equals(s2); 39 | }else if(s1.length() != s2.length()){ 40 | return false; 41 | } 42 | int[] ck = new int[26]; 43 | for(int i = 0;i> fourSum(int[] num, int target) { 26 | // Start typing your Java solution below 27 | // DO NOT write main() function 28 | ArrayList> res = new ArrayList>(); 29 | if(num == null || num.length <= 3){ 30 | return res; 31 | } 32 | Arrays.sort(num); 33 | for(int i = 0 ; i < num.length - 3; i ++){ 34 | if(i != 0 && num[i] == num[i - 1]){continue;} 35 | for(int j = num.length -1; j > i + 2; j--){ 36 | if(j != num.length -1 && num[j] == num[j + 1]){continue;} 37 | int low = i + 1; 38 | int high = j -1; 39 | while(low < high){ 40 | if(low != i+1 && num[low] == num[low -1]){ 41 | low++; 42 | }else if(high != j -1 && num[high] == num[high+1]){ 43 | high--; 44 | }else{ 45 | int sum = num[i] + num[low] + num[high] + num[j]; 46 | if(sum == target){ 47 | ArrayList adds = new ArrayList(); 48 | adds.add(num[i]); 49 | adds.add(num[low]); 50 | adds.add(num[high]); 51 | adds.add(num[j]); 52 | res.add(adds); 53 | high--;low++; 54 | }else if(sum > target){ 55 | high--; 56 | }else{ 57 | low++; 58 | } 59 | } 60 | } 61 | } 62 | } 63 | return res; 64 | } 65 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Two Sum.txt: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public int[] twoSum(int[] numbers, int target) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | int[] res = new int[2]; 7 | res[0] = -1; 8 | res[1] = -1; 9 | if(numbers.length <= 1){ 10 | return res; 11 | } 12 | twoLoop(numbers,target,res); 13 | return res; 14 | } 15 | 16 | /// space O(n) , time O(n) 17 | int[] hashMethod(int[] numbers,int target,int[] res){ 18 | HashMap checks = new HashMap(); 19 | for(int i = 0 ; i < numbers.length; i++){ 20 | if(checks.containsKey(numbers[i])){ 21 | res[0] = checks.get(numbers[i]) + 1; 22 | res[1] = i + 1; 23 | break; 24 | }else{ 25 | checks.put(target - numbers[i], i); 26 | } 27 | } 28 | return res; 29 | } 30 | 31 | /// space O(1) , time O(n^2) 32 | int[] twoLoop(int[] numbers,int target,int[] res){ 33 | for(int i = 0 ; i < numbers.length; i++){ 34 | for(int j = i + 1; j< numbers.length; j++){ 35 | if(numbers[i] + numbers[j] == target){ 36 | res[0] = i + 1; 37 | res[1] = j + 1; 38 | break; 39 | } 40 | } 41 | } 42 | return res; 43 | } 44 | 45 | 46 | // if has duplicate number in the given array 47 | // return multi solutions 48 | // space O(n) , time O(n) 49 | ArrayList duplicateMethod(int[] numbers,int target){ 50 | ArrayList res = new ArrayList(); 51 | HashMap> checks = new HashMap>(); 52 | for(int i = 0 ; i < numbers.length; i++){ 53 | if(checks.containsKey(numbers[i])){ 54 | List indexes = checks.get(numbers[i]); 55 | for(Integer index : indexes){ 56 | int[] tmps = new int[2]; 57 | tmps[0] = index; 58 | tmps[1] = i; 59 | res.add(tmps); 60 | } 61 | } 62 | if(checks.containsKey(target - numbers[i])){ 63 | checks.get(target - numbers[i]).add(i); 64 | }else{ 65 | List tmps = new ArrayList(); 66 | tmps.add(i); 67 | checks.put(target - numbers[i],tmps); 68 | } 69 | } 70 | return res; 71 | } 72 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Binary Tree Level Order Traversal.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList> levelOrder(TreeNode root) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | return printLevel(root); 15 | } 16 | 17 | //for iterative solution 18 | ArrayList> ite(TreeNode root){ 19 | ArrayList> res = new ArrayList>(); 20 | ArrayList adds = new ArrayList(); 21 | if(root == null){ 22 | return res; 23 | } 24 | Queue ques = new LinkedList(); 25 | int cur = 1; 26 | int next = 0; 27 | ques.add(root); 28 | while(ques.size() > 0){ 29 | TreeNode curnode = ques.poll(); 30 | adds.add(curnode.val); 31 | if(curnode.left != null){ 32 | ques.add(curnode.left); 33 | next++; 34 | } 35 | if(curnode.right != null){ 36 | ques.add(curnode.right); 37 | next++; 38 | } 39 | cur--; 40 | if(cur == 0){ 41 | cur = next; 42 | next = 0; 43 | res.add(new ArrayList(adds)); 44 | adds.clear(); 45 | } 46 | } 47 | return res; 48 | } 49 | 50 | //for recursive solution 51 | void rec(TreeNode node,int level,ArrayList adds){ 52 | if(node == null){ 53 | return; 54 | } 55 | if(level== 1){ 56 | adds.add(node.val); 57 | }else{ 58 | rec(node.left,level-1,adds); 59 | rec(node.right,level-1,adds); 60 | } 61 | } 62 | 63 | int maxHeight(TreeNode node){ 64 | if(node == null){ 65 | return 0; 66 | } 67 | int left = maxHeight(node.left); 68 | int right = maxHeight(node.right); 69 | return Math.max(left,right) + 1; 70 | } 71 | 72 | ArrayList> printLevel(TreeNode node){ 73 | ArrayList> res = new ArrayList>(); 74 | int height = maxHeight(node); 75 | for(int i = 1; i <= height; i++){ 76 | ArrayList adds = new ArrayList(); 77 | rec(node,i,adds); 78 | res.add(adds); 79 | } 80 | return res; 81 | } 82 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Surrounded Regions.txt: -------------------------------------------------------------------------------- 1 | Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. 2 | 3 | A region is captured by flipping all 'O's into 'X's in that surrounded region . 4 | 5 | For example, 6 | 7 | X X X X 8 | X O O X 9 | X X O X 10 | X O X X 11 | After running your function, the board should be: 12 | 13 | X X X X 14 | X X X X 15 | X X X X 16 | X O X X 17 | 18 | ============================================================ 19 | 20 | use dfs or bfs, search from edges. 21 | will not pass large set if use reccurence, use queue and bfs instead. 22 | 23 | Solutions: 24 | 25 | public class Solution { 26 | public void solve(char[][] board) { 27 | // Start typing your Java solution below 28 | // DO NOT write main() function 29 | if(board.length == 0 || board[0].length == 0){ 30 | return; 31 | } 32 | int n = board.length; 33 | int m = board[0].length; 34 | for(int i = 0 ; i < m ; i++){ 35 | bfs(board,0,i); 36 | bfs(board,n-1,i); 37 | } 38 | for(int j = 0 ; j < n ;j++){ 39 | bfs(board,j,0); 40 | bfs(board,j,m-1); 41 | } 42 | for(int i = 0 ; i < n ;i++){ 43 | for(int j = 0 ; j < m ;j++){ 44 | if(board[i][j] == 'O'){ 45 | board[i][j] = 'X'; 46 | }else if(board[i][j] == '+'){ 47 | board[i][j] = 'O'; 48 | } 49 | } 50 | } 51 | } 52 | 53 | void bfs(char[][] board,int i,int j){ 54 | Queue ques = new LinkedList(); 55 | visit(board,i,j,ques); 56 | while(!ques.isEmpty()){ 57 | int tmp = ques.poll(); 58 | int ia = tmp / board[0].length; 59 | int ib = tmp % board[0].length; 60 | visit(board,ia+1,ib,ques); 61 | visit(board,ia,ib+1,ques); 62 | visit(board,ia-1,ib,ques); 63 | visit(board,ia,ib-1,ques); 64 | } 65 | } 66 | 67 | void visit(char[][] board,int i, int j,Queue ques){ 68 | if(i >= board.length || i < 0 || j >= board[0].length || j < 0){ 69 | return; 70 | } 71 | if(board[i][j] == 'O'){ 72 | board[i][j] = '+'; 73 | ques.add(i * board[0].length + j); 74 | } 75 | } 76 | 77 | ///dfs will not pass the large set 78 | void dfs(char[][] board,int i,int j){ 79 | if(i >= board.length || i < 0 || j >= board[0].length || j < 0){ 80 | return; 81 | } 82 | if(board[i][j] == 'O'){ 83 | board[i][j] = '+'; 84 | 85 | dfs(board,i-1,j); 86 | dfs(board,i+1,j); 87 | dfs(board,i,j+1); 88 | dfs(board,i,j-1); 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Swap Nodes in Pairs.txt: -------------------------------------------------------------------------------- 1 | Given a linked list, swap every two adjacent nodes and return its head. 2 | 3 | For example, 4 | Given 1->2->3->4, you should return the list as 2->1->4->3. 5 | 6 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 7 | 8 | ======================================= 9 | 10 | take care: 11 | use three pointer to exchange the node postion and update the pointer 12 | 13 | 14 | Soltuion: 15 | /** 16 | * Definition for singly-linked list. 17 | * public class ListNode { 18 | * int val; 19 | * ListNode next; 20 | * ListNode(int x) { 21 | * val = x; 22 | * next = null; 23 | * } 24 | * } 25 | */ 26 | public class Solution { 27 | public ListNode swapPairs(ListNode head) { 28 | // Start typing your Java solution below 29 | // DO NOT write main() function 30 | if(head == null || head.next == null){ 31 | return head; 32 | } 33 | return traversal2(head); 34 | } 35 | 36 | //traversal solution with a extra node 37 | ListNode traverse(ListNode head){ 38 | ListNode dm = new ListNode(0); 39 | dm.next = head; 40 | ListNode pre = dm; 41 | ListNode cur = head; 42 | ListNode next = head.next; 43 | while(cur != null && next != null){ 44 | pre.next = next; 45 | cur.next = next.next; 46 | next.next = cur; 47 | //update 48 | pre = cur; 49 | cur = cur.next; 50 | if(cur == null){ 51 | break; 52 | }else{ 53 | next = cur.next; 54 | } 55 | } 56 | return dm.next; 57 | } 58 | 59 | //recursive solution 60 | ListNode recursive(ListNode head){ 61 | if(head == null || head.next == null){ 62 | return head; 63 | } 64 | ListNode next = recursive(head.next.next); 65 | ListNode pre = head; 66 | ListNode cur = head.next; 67 | cur.next = pre; 68 | pre.next = next; 69 | return cur; 70 | } 71 | 72 | //traversal solution without extra node 73 | ListNode traversal2(ListNode head){ 74 | ListNode pre = null; 75 | ListNode cur = head; 76 | ListNode next = head.next; 77 | while(next != null){ 78 | cur.next = next.next; 79 | next.next = cur; 80 | if(pre != null){ 81 | pre.next = next; 82 | }else{ 83 | head = next; 84 | } 85 | pre = cur; 86 | cur = cur.next; 87 | if(cur != null){ 88 | next = cur.next; 89 | }else{ 90 | next = null; 91 | } 92 | } 93 | return head; 94 | } 95 | } -------------------------------------------------------------------------------- /leetCode/Version2.0/Palindrome Number.txt: -------------------------------------------------------------------------------- 1 | Determine whether an integer is a palindrome. Do this without extra space. 2 | 3 | Some hints: 4 | Could negative integers be palindromes? (ie, -1) 5 | 6 | If you are thinking of converting the integer to string, note the restriction of using extra space. 7 | 8 | You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? 9 | 10 | There is a more generic way of solving this problem. 11 | 12 | 13 | ============================================== 14 | 15 | public class Solution { 16 | public boolean isPalindrome(int x) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | if( x < 0 ){ 20 | return false; 21 | }else if( x == 0){ 22 | return true; 23 | } 24 | number y = new number(x); 25 | return isWithRec(x,y); 26 | } 27 | 28 | //solution with transform to string 29 | // space O(n) 30 | boolean isWithStr(int x){ 31 | 32 | StringBuffer str = new StringBuffer(); 33 | while(x > 0 ){ 34 | str.append(x % 10); 35 | x = x / 10; 36 | } 37 | int low = 0; 38 | int high = str.length() -1; 39 | while(low < high){ 40 | if(str.charAt(low) != str.charAt(high)){ 41 | return false; 42 | } 43 | low++;high--; 44 | } 45 | return true; 46 | } 47 | 48 | //solution with no extra space 49 | 50 | boolean isWithNoExtra(int x){ 51 | int pos = 1; 52 | int tmp = x; 53 | while(tmp >= 10){ 54 | pos *= 10; 55 | tmp /= 10; 56 | } 57 | while(x >= 10){ 58 | if( x / pos != x % 10){ 59 | return false; 60 | } 61 | x = x % pos / 10; 62 | pos /= 100; 63 | } 64 | return true; 65 | } 66 | 67 | //solution with just one traverse 68 | //for some un palindrome number, it maybe overflow 69 | // but the results is correct 70 | boolean isWithOne(int x){ 71 | int tmpx = 0; 72 | int t = x; 73 | while(x > 0){ 74 | tmpx = tmpx * 10 + x % 10; 75 | x /= 10; 76 | } 77 | return tmpx == t; 78 | } 79 | 80 | class number{ 81 | int y; 82 | public number(int t){ 83 | this.y = t; 84 | } 85 | } 86 | 87 | ///solve with recurrence 88 | boolean isWithRec(int x,number y){ 89 | if(x == 0){ 90 | return true; 91 | } 92 | if(isWithRec(x/10,y) && (x % 10 == y.y % 10)){ 93 | y.y = y.y / 10; 94 | return true; 95 | }else{ 96 | return false; 97 | } 98 | } 99 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/Set Matrix Zeroes.txt: -------------------------------------------------------------------------------- 1 | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 2 | 3 | Follow up: 4 | Did you use extra space? 5 | A straight forward solution using O(mn) space is probably a bad idea. 6 | A simple improvement uses O(m + n) space, but still not the best solution. 7 | Could you devise a constant space solution? 8 | 9 | ======================================================================== 10 | 11 | Complexity : time O(mn) space : O(1) 12 | 13 | take care : for O(1) space solution, start from matrix[1][1] not matrix[0][0] 14 | Solution: 15 | public class Solution { 16 | public void setZeroes(int[][] matrix) { 17 | // Start typing your Java solution below 18 | // DO NOT write main() function 19 | toSolve(matrix); 20 | } 21 | 22 | //space o(1) time o(mn) 23 | void toSolve(int[][] matrix){ 24 | if(matrix == null || matrix.length == 0){ 25 | return; 26 | } 27 | int n = matrix.length; 28 | int m = matrix[0].length; 29 | boolean col = false; 30 | boolean row = false; 31 | for(int i = 0 ; i < n;i++){ 32 | if(matrix[i][0] == 0){ 33 | col = true; 34 | } 35 | } 36 | for(int j = 0 ; j< m; j++){ 37 | if(matrix[0][j] == 0){ 38 | row = true; 39 | } 40 | } 41 | for(int i = 1 ; i < n ;i++){ 42 | for(int j = 1 ; j < m;j++){ 43 | if(matrix[i][j] == 0){ 44 | matrix[0][j] = 0; 45 | matrix[i][0] = 0; 46 | } 47 | } 48 | } 49 | for(int i = 1 ; i < n; i++){ 50 | for(int j = 1 ; j < m; j++){ 51 | if(matrix[0][j] == 0 || matrix[i][0] == 0){ 52 | matrix[i][j] = 0; 53 | } 54 | } 55 | } 56 | if(col){ 57 | for(int i = 0 ; i < n ; i++){ 58 | matrix[i][0] = 0; 59 | } 60 | } 61 | if(row){ 62 | for(int i = 0 ; i < m;i++){ 63 | matrix[0][i] = 0; 64 | } 65 | } 66 | } 67 | 68 | 69 | //space o(m+n) time o(mn) 70 | void solve(int[][] matrix){ 71 | if(matrix == null || matrix.length == 0){ 72 | return ; 73 | } 74 | int n = matrix.length; 75 | int m = matrix[0].length; 76 | boolean[] rows = new boolean[n]; 77 | boolean[] cols = new boolean[m]; 78 | for(int i = 0 ; i < n;i++){ 79 | for(int j = 0 ; j < m;j++){ 80 | if(matrix[i][j] == 0){ 81 | rows[i] = true; 82 | cols[j] = true; 83 | } 84 | } 85 | } 86 | for(int i = 0 ; i < n; i++){ 87 | for(int j = 0 ; j < m ;j++){ 88 | if(rows[i] || cols[j]){ 89 | matrix[i][j] = 0; 90 | } 91 | } 92 | } 93 | } 94 | } -------------------------------------------------------------------------------- /leetCode/Leetcode/String to Integer (atoi).txt: -------------------------------------------------------------------------------- 1 | Implement atoi to convert a string to an integer. 2 | 3 | Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. 4 | 5 | Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. 6 | 7 | Requirements for atoi: 8 | The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. 9 | 10 | The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. 11 | 12 | If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. 13 | 14 | If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. 15 | 16 | ========================================== 17 | 18 | Complexity: O(n) 19 | 20 | take care some cases: 21 | 1. "" xxxx " , int head and tail, some blanks 22 | 2. "+/-xxx" , take care the sign. 23 | 3. "1a", return 1 24 | 4. biger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE,use a long to record the value 25 | 26 | Solution: 27 | 28 | public class Solution { 29 | public class Solution { 30 | public int atoi(String str) { 31 | // Start typing your Java solution below 32 | // DO NOT write main() function 33 | if(str == null || str.length() == 0){ 34 | return 0; 35 | } 36 | int start = 0; 37 | int end = str.length() -1; 38 | while(start < str.length() && str.charAt(start) == ' '){start++;}; 39 | while(end >= 0 && str.charAt(end) == ' '){end--;}; 40 | long res = 0; 41 | boolean sign = false; 42 | if(start > end){ 43 | return 0; 44 | }else if(start == end){ 45 | if(str.charAt(start) >= '0' && str.charAt(start) <= '9'){ 46 | return str.charAt(start) - '0'; 47 | }else{ 48 | return 0; 49 | } 50 | }else{ 51 | if(str.charAt(start) == '+' || str.charAt(start) == '-'){ 52 | sign = str.charAt(start) == '-'?true:false; 53 | start++; 54 | } 55 | for(int i = start ; i <= end; i++){ 56 | if(str.charAt(i) > '9' || str.charAt(i) < '0'){ 57 | return (int)res; 58 | } 59 | if(sign){ 60 | res = res * 10 + -1 * (str.charAt(i) - '0'); 61 | }else{ 62 | res = res * 10 + str.charAt(i) - '0'; 63 | } 64 | if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE){ 65 | return Integer.MAX_VALUE < res?Integer.MAX_VALUE:Integer.MIN_VALUE; 66 | } 67 | } 68 | } 69 | return (int)res; 70 | } 71 | } --------------------------------------------------------------------------------