LeetCode – Range Sum Query 2D – Immutable (Java)

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Analysis Since the assumption is that there are many calls to sumRegion method, we should use some extra space to store the intermediate results. The solution is … Read more

LeetCode – Combination Sum II (Java)

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. Each number in C may only be used ONCE in the combination. Note: 1) All numbers (including target) will be positive integers. 2) Elements in a combination (a1, a2, … … Read more

LeetCode – Binary Tree Level Order Traversal II (Java)

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. For example, given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its level order traversal as [[15,7], [9,20],[3]] Java Solution public List<ArrayList<Integer>> levelOrderBottom(TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();   if(root == null){ return result; … Read more

LeetCode – Binary Tree Level Order Traversal (Java)

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its level order traversal as [[3], [9,20], [15,7]] Java Solution 1 It is obvious that this problem can … Read more

LeetCode – Letter Combinations of a Phone Number (Java)

Given a digit string, return all possible letter combinations that the number could represent. (Check out your cellphone to see the mappings) Input:Digit string “23”, Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]. Java Solution 1 – DFS This problem can be solves by a typical DFS algorithm. DFS problems are very similar … Read more

LeetCode – Pascal’s Triangle II (Java)

Given an index k, return the kth row of the Pascal’s triangle. For example, when k = 3, the row is [1,3,3,1]. Analysis This problem is related to Pascal’s Triangle which gets all rows of Pascal’s triangle. In this problem, only one row is required to return. Java Solution public List<Integer> getRow(int rowIndex) { ArrayList<Integer> … Read more

LeetCode – Palindrome Partitioning II (Java)

Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. For example, given s = “aab”, return 1 since the palindrome partitioning [“aa”,”b”] could be produced using 1 cut. Analysis This problem is similar to Palindrome Partitioning. It … Read more