摘要:Problem:Given a set of distinct integers,S, return all possible subsets.Note:Elements in a subset must be in non-descending order.The solution set must not contain duplicate subsets.For example,IfS=[1,2,3], a solution is:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []]Analysis:Simple backt...
阅读全文
摘要:Problem:Given two integersnandk, return all possible combinations ofknumbers out of 1 ...n.For example,Ifn= 4 andk= 2, a solution is:[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]Analysis:Simple backtracking problem.Code: 1 class Solution { 2 public: 3 vector<vector<int> > res; 4 int kk;..
阅读全文
摘要:Problem:Write an efficient algorithm that searches for a value in anmxnmatrix. This matrix has the following properties:Integers in each row are sorted from left to right.The first integer of each row is greater than the last integer of the previous row.For example,Consider the following matrix:[ [.
阅读全文
摘要:Problem:Given amxnmatrix, if an element is 0, set its entire row and column to 0. Do it in place.Follow up:Did you use extra space?A straight forward solution using O(mn) space is probably a bad idea.A simple improvement uses O(m+n) space, but still not the best solution.Could you devise a constant
阅读全文
摘要:Problem:Given an absolute path for a file (Unix-style), simplify it.For example,path="/home/", =>"/home"path="/a/./b/../../c/", =>"/c"Corner Cases:Did you consider the case wherepath="/../"?In this case, you should return"/".Another c
阅读全文
摘要:Problem:Given amxngrid filled with non-negative numbers, find a path from top left to bottom right whichminimizesthe sum of all numbers along its path.Note:You can only move either down or right at any point in time.Analysis:Simple DP problem, always choose the minimum path preceed the current posit
阅读全文
摘要:Problem:Follow up for "Unique Paths":Now consider if some obstacles are added to the grids. How many unique paths would there be?An obstacle and empty space is marked as1and0respectively in the grid.For example,There is one obstacle in the middle of a 3x3 grid as illustrated below.[ [0,0,0
阅读全文
摘要:Problem:Given a list, rotate the list to the right bykplaces, wherekis non-negative.For example:Given1->2->3->4->5->NULLandk=2,return4->5->1->2->3->NULL.Analysis:The first thought is to use the same strategy as in "Remove Kth Node in List" -- using two pointer
阅读全文
摘要:Problem:Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.Determine if you are able to reach the last index.For example:A =[2,3,1,1,4], returntrue.A =[3,2,1,0,4], return
阅读全文
摘要:Problem:Analysis:Naive solution which compute every possible subarray sum and find the maximum need O(n^3), which is unbearable.A O(n) solutoin can be found based on the fact that. If the current sum is greater than or equal to 0, we keep add new element to it. If the current sum is less than 0, we
阅读全文
摘要:Problem:Given an array of strings, return all groups of strings that are anagrams.Note: All inputs will be in lower-case.Analysis:anagrams are those strings that consist of same characters but in different order. A very simple way to solve the problem is try to find each string's anagrams. This
阅读全文
摘要:Problem:Given a collection of numbers, return all possible permutations.For example,[1,2,3]have the following permutations:[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2], and[3,2,1].Analysis:It's a backtracking problem. In order to make sure that we don't access the same element multiple times, we
阅读全文
摘要:Problem:Given a set of candidate numbers (C) and a target number (T), find all unique combinations inCwhere the candidate numbers sums toT.Thesamerepeated number may be chosen fromCunlimited number of times.Note:All numbers (including target) will be positive integers.Elements in a combination (a1,a
阅读全文
摘要:Problem:Say you have an array for which theithelement is the price of a given stock on dayi.Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transact
阅读全文
摘要:Problem:Mergeksorted linked lists and return it as one sorted list. Analyze and describe its complexity.Analysis:Since each list is sorted, the second element won't be merged into the final list until the first element is merged. So we can scan the head of each list and find the minimum element
阅读全文
摘要:Problem:Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.For example, givenn= 3, a solution set is:"((()))", "(()())", "(())()", "()(())", "()()()"Analysis:Also a backtracking problem. Each time eit
阅读全文
摘要:Problem:Given a digit string, return all possible letter combinations that the number could represent.A mapping of digit to letters (just like on the telephone buttons) is given below.Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be&q
阅读全文
摘要:Problem:Given an arraySofnintegers, are there elementsa,b,c, anddinSsuch thata+b+c+d= target? Find all unique quadruplets in the array which gives the sum of target.Note:Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie,a?b?c?d)The solution set must not contain duplicate quadru
阅读全文
摘要:Problem:Given an arraySofnintegers, find three integers inSsuch 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. For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is clo...
阅读全文
摘要:Problem:Given an arraySofnintegers, are there elementsa,b,cinSsuch thata+b+c= 0? Find all unique triplets in the array which gives the sum of zero.Note:Elements in a triplet (a,b,c) must be in non-descending order. (ie,a?b?c)The solution set must not contain duplicate triplets. For example, given...
阅读全文
摘要:Problem:Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.Analysis:In roman number system, there are 3 special cases1. 900 or 4002. 90 or 403. 9 or 4Process the integer number digit by digit, if it's 9 or 4, process it separately. Then if i
阅读全文
摘要:Problem:Givennnon-negative integersa1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis 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.No
阅读全文
摘要:Problem:The string"PAYPALISHIRING"is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)P A H NA P L S I I GY I RAnd then read line by line:"PAHNAPLSIIGYIR"Write the code that will take a st
阅读全文
摘要:Problem: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 lengt
阅读全文
摘要:Problem: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.Input:(2 -> 4 -> 3) + (5 -> 6 -> 4)Output:7 -> 0 -> 8Analysis:Simp
阅读全文
摘要:Problem:Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.An example is the root-to-leaf path1->2->3which represents the number123.Find the total sum of all root-to-leaf numbers.For example, 1 / \ 2 3The root-to-leaf path1->2represents the nu
阅读全文
摘要:Problem:Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.For example,"A man, a plan, a canal: Panama"is a palindrome."race a car"isnota palindrome.Note:Have you consider that the string might be empty? This is a good que
阅读全文
摘要:Probelm:Say you have an array for which theithelement is the price of a given stock on dayi.If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.Analysis:There's obviously a O(n^2) algorithm:
阅读全文
摘要:Problem:Given an indexk, return thekthrow of the Pascal's triangle.For example, givenk= 3,Return[1,3,3,1].Note:Could you optimize your algorithm to use onlyO(k) extra space?Analysis:The direct way to solve the problem is to use the formula: C(i, k) = k! / (i! * (k-i)!). But it will exceed the in
阅读全文
摘要:Problem:GivennumRows, generate the firstnumRowsof Pascal's triangle.For example, givennumRows= 5,Return[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]Analysis:There two ways to solve the problem, either compute each row element separately or use inductive method.The latter cost much more le...
阅读全文
摘要:Problem:Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.For example:Given the below binary tree andsum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1return[ [5...
阅读全文
摘要:Problem:The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...1is read off as"one 1"or11.11is read off as"two 1s"or21.21is read off as"one 2, thenone 1"or1211.Given an integern, generate thenthsequence.Note: The sequence
阅读全文
摘要:Problem:Given an array where elements are sorted in ascending order, convert it to a height balanced BST.Analysis:Remember a binary search tree's inorder treversal is a sorted array.To convert in the contrary direction, we need to create a node with the middle value of the given array and then c
阅读全文
摘要:Problem:Given two sorted integer arrays A and B, merge B into A as one sorted array.Note:You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B aremandnrespectively.Analysis:To finish the task efficiently, merge should started from th
阅读全文
摘要:Probelm:Follow up for "Remove Duplicates":What if duplicates are allowed at mosttwice?For example,Given sorted array A =[1,1,1,2,2,3],Your function should return length =5, and A is now[1,1,2,2,3].Analysis:One pass algorithm, with the help of an extra counter which keeps recoreds of the nu
阅读全文
摘要:Probelm:You are climbing a stair case. It takesnsteps to reach to the top.Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?Analysis:Simplest DP problem,Sn = Sn-1 + Sn-2 with S1 = 1 and S2 = 2;Code: 1 class Solution { 2 public: 3 int climbStairs(int ...
阅读全文
摘要:Problem:Given two binary strings, return their sum (also a binary string).For example,a ="11"b ="1"Return"100".Analysis:Three main steps: 1. add a and b until meet one's end; 2. process the remaining part of the the other string; 3. process the carry bit.Simulation
阅读全文
摘要:Problem:Validate if a given string is numeric.Some examples:"0"=>true" 0.1 "=>true"abc"=>false"1 a"=>false"2e10"=>trueNote:It is intended for the problem statement to be ambiguous. You should gather all requirements up front before imp
阅读全文
摘要:Problem:A robot is located at the top-left corner of amxngrid (marked 'Start' in the diagram below).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).How many poss
阅读全文
摘要:Problem:Implement pow(x,n).Analysis:Notice n may be negative numbers.Simply use for loop to implement is okay when n is small. When n is large enough, it may cause Time Limit Exceeded error. In this way, the time complexity is O(n).There's a recursive implementation method can reduce the complex
阅读全文
摘要:Problem:Determine if a Sudoku is valid, according to:Sudoku Puzzles - The Rules.The Sudoku board could be partially filled, where empty cells are filled with the character'.'.A partially filled sudoku which is valid.Analysis:Simulation problem, the nice part here is use a same function for t
阅读全文
摘要:Problem:Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.You may assume no duplicates in the array.Here are few examples.[1,3,5,6], 5 → 2[1,3,5,6], 2 → 1[1,3,5,6], 7 → 4[1,3,5,6], 0 → 0Analysis:A
阅读全文
摘要:Problem:Given a linked list, swap every two adjacent nodes and return its head.For example,Given1->2->3->4, you should return the list as2->1->4->3.Your algorithm should use only constant space. You maynotmodify the values in the list, only nodes itself can be changed.Analysis:One
阅读全文
摘要:Problem: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.Analysis:like merge sort.Time complexity is O(m+n), Space complexity is O(m+n)Code: 1 /** 2 * Definition for singly-linked list. 3 * public class Lis..
阅读全文
摘要:Problem:Given a string containing just the characters'(',')','{','}','['and']', determine if the input string is valid.The brackets must close in the correct order,"()"and"()[]{}"are all valid but"(]"and"([)]"are
阅读全文
摘要:Problem:Given a linked list, remove thenthnode from the end of list and return its head.For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.Note:Givennwill always be valid.Try to do this in one
阅读全文
摘要:Problem:Write a function to find the longest common prefix string amongst an array of strings.Analysis:Each time take a character from the first string and compare it with other strings' same position character.If reaching some end of some string or find a mismatch, then the longest common prefi
阅读全文
摘要:Problem:Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.Analysis:Some Roman Number examples can be seen here:http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm.Use a one pass scan to decide whether add or subtract a number from current
阅读全文