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

LeetCode – Search a 2D Matrix II (Java)

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. For example, consider the following matrix: [ [1, 4, 7, … Read more

LeetCode – Longest Increasing Subsequence (Java)

Given an unsorted array of integers, find the length of longest increasing subsequence. For example, given [10, 9, 2, 5, 3, 7, 101, 18], the longest increasing subsequence is [2, 3, 7, 101]. Therefore the length is 4. Java Solution 1 – Naive Let max[i] represent the length of the longest increasing subsequence so far. … Read more

LeetCode – Power of Three (Java)

Given an integer, write a function to determine if it is a power of three. Java Solution 1 – Iteration public boolean isPowerOfThree(int n) { if(n==1) return true;   boolean result = false;   while(n>0){ int m = n%3; if(m==0){ n=n/3; if(n==1) return true; }else{ return false; } }   return result; }public boolean isPowerOfThree(int … Read more