02 2014 档案
摘要:TreeBinary Tree Preorder TraversalBinary Tree Inorder TraversalBinary Tree Postorder TraversalBinary Tree Level Order TraversalBinary Tree Level Order Traversal IIBinary Tree Zigzag Level Order TraversalMaximum Depth of Binary TreeMinimum Depth of Binary TreePath SumPath Sum IIBinary Tree Maximum Pa
阅读全文
摘要:Given an integern, generate a square matrix filled with elements from 1 ton2in spiral order.For example,Givenn=3,You should return the following matrix:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]生成的过程为 (1) 横向生成 1,2 (2) 纵向生成 3,4 (3) 横向生成 5,6 (4) 纵向生成 7,8 (5) 生成 9public class ...
阅读全文
摘要:Given a stringSand a stringT, count the number of distinct subsequences ofTinS.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"
阅读全文
摘要:Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing its structure.Ref:http://fisherlei.blogspot.com/20...
阅读全文
摘要:Given an array of integers, every element appearsthreetimes except for one. Find that single one.Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?Ref :http://fisherlei.blogspot.com/2013/11/leetcode-single-number-ii-solution.html[Thoughts]
阅读全文
摘要:Given an absolute path for a file (Unix-style), simplify it.For example,path="/home/", =>"/home"path="/a/./b/../../c/", =>"/c"click to show corner cases.Corner Cases:Did you consider the case wherepath="/../"?In this case, you should return&quo
阅读全文
摘要:Evaluate the value of an arithmetic expression inReverse Polish Notation.Valid operators are+,-,*,/. Each operand may be an integer or another express...
阅读全文
摘要:Givennpoints on a 2D plane, find the maximum number of points that lie on the same straight line.思路: 从 points[] 中依次取出一个点,然后依次和后面一个点组成一条直线。 y = ax+b;然后...
阅读全文
摘要:Sort a linked list inO(nlogn) time using constant space complexity.Merge sort先根据mid node把list 分割为 单个 node ,然后merge/** * Definition for singly-linked l...
阅读全文
摘要:Sort a linked list using insertion sort.思路: 建立一个fake head, 依次从list中取出一个node,插入到 fake head 的list中去,从小到大排列。public class Solution { public ListNode insertionSortList(ListNode head) { ListNode prehead = new ListNode(Integer.MIN_VALUE); ListNode runner = head; while(runner != null...
阅读全文
摘要:Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:getandset.get(key)- Get the valu...
阅读全文
摘要:Given a singly linked listL:L0→L1→…→Ln-1→Ln,reorder it to:L0→Ln→L1→Ln-1→L2→Ln-2→…You must do this in-place without altering the nodes' values.For exam...
阅读全文
摘要:Given a stringsand a dictionary of wordsdict, add spaces insto construct a sentence where each word is a valid dictionary word.Return all such possible sentences.For example, givens="catsanddog",dict=["cat", "cats", "and", "sand", "dog"].A
阅读全文
摘要:Given a stringsand a dictionary of wordsdict, determine ifscan be segmented into a space-separated sequence of one or more dictionary words.For example, givens="leetcode",dict=["leet", "code"].Return true because"leetcode"can be segmented as"leet code&quo
阅读全文
摘要:A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.Return a deep copy of the list.Ref:http://fisherlei.blogspot.com/2013/11/leetcode-copy-list-with-random-pointer.html如图分三步:http://lh6.ggpht.com/-xlfWkNgeNhI/Uomwl3lB47I/A
阅读全文
摘要:Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.Follow up:Can you solve it without using extra space?解题思路:双指针, 一个指针一次走一步,一个指针一次走两步, 如果有环,定相遇。然后将快指针移到头部,再一次走一步,当两只真再次相遇的时候就是指针的头/** * Definition for singly-linked list. * class ListNode { * int val; * ...
阅读全文
摘要:Given an array of integers, every element appearstwiceexcept for one. Find that single one.Could you implement it without using extra memory?Ref:http://www.cnblogs.com/feiling/p/3349654.html[解题思路]以前看书时遇到过,一个数组中有一个元素出现一次,其他每个元素都出现两次要求空间复杂度为O(1)由于两个相同的元素异或的结果为0,而0^a==a,将数组中所有元素都进行异或,得到结果就是只出现一次的元素publ
阅读全文
摘要:There areNchildren standing in a line. Each child is assigned a rating value.You are giving candies to these children subjected to the following requi...
阅读全文
摘要:There areNgas stations along a circular route, where the amount of gas at stationiisgas[i].You have a car with an unlimited gas tank and it costscost[...
阅读全文
摘要:Given a linked list, determine if it has a cycle in it.Follow up:Can you solve it without using extra space?两个指针,一个一次走两步,一个一次走一步,相遇说明有环/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * ...
阅读全文
摘要:Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors.OJ's undirected graph serialization:Nodes are labeled uniquely.We use#as a separator for each node, and,as a separator for node label and each neighbor of the node.As an example, consider the serialized g
阅读全文
摘要:Given a binary tree, return thepostordertraversal of its nodes' values.For example:Given binary tree{1,#,2,3}, 1 \ 2 / 3return[3,2,1].Note:Recursive solution is trivial, could you do it iteratively?Ref:http://www.cnblogs.com/feiling/p/3426486.html[解题思路]后序遍历的非递归相对来说比较难,根节点需要在其左右孩子都访问结束后...
阅读全文
摘要:Given a binary tree, return thepreordertraversal of its nodes' values.For example:Given binary tree{1,#,2,3}, 1 \ 2 / 3return[1,2,3].Note:Recursive solution is trivial, could you do it iteratively?Using Stack/** * Definition for binary tree * public class TreeNode { * int val; * ...
阅读全文
摘要: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 a...
阅读全文
摘要: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 a...
阅读全文
摘要: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...
阅读全文
摘要:Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.For example, given the following triangle[ [2], [3,4], [6,5,7], [4,1,8,3]]The minimum path sum from top to bottom is11(i.e.,2+3+5+1= 11).Note:Bonus point if you are a...
阅读全文
摘要:Givennnon-negative integersa1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of ...
阅读全文
摘要:Given a binary tree, flatten it to a linked list in-place.For example,Given 1 / \ 2 5 / \ \ 3 4 6The flattened t...
阅读全文
摘要:Given a binary tree, return thebottom-up level ordertraversal of its nodes' values. (ie, from left to right, level by level from leaf to root).For example:Given binary tree{3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7return its bottom-up level order traversal as:[ [15,7] [9,20], [3],] 解题思...
阅读全文
摘要: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?滚动数组 + 从后往前计算 避免重复public class Solution { public ArrayList getRow(int rowIndex) { ArrayList res = new ArrayList(); i...
阅读全文
摘要: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.从
阅读全文
摘要: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]]第三行开始,每行除边界元素外,每个元素ai都是由ai-1 + ai构成 1 public class Solution { 2 public ArrayList> generate(int numRows) { 3 ArrayList> res = new ArrayLis...
阅读全文
摘要:You are given a string,S, and a list of words,L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenati...
阅读全文
摘要: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 m...
阅读全文
摘要:Givenn, generate all structurally uniqueBST's(binary search trees) that store values 1...n.For example,Givenn= 3, your program should return all 5 uni...
阅读全文
摘要:Givenn, how many structurally uniqueBST's(binary search trees) that store values 1...n?For example,Givenn= 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 ...
阅读全文
摘要:Given a string containing just the characters'('and')', find the length of the longest valid (well-formed) parentheses substring.For"(()", the longest valid parentheses substring is"()", which has length = 2.Another example is")()())", where the longest
阅读全文
摘要:Given a binary tree, find the maximum path sum.The path may start and end at any node in the tree.For example:Given the below binary tree, 1 ...
阅读全文
摘要: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 string and
阅读全文
摘要:Write a function to find the longest common prefix string amongst an array of strings.public class Solution { public String longestCommonPrefix(String[] strs) { String compare =""; if(strs.length == 0) return compare; compare = strs[0]; for(int i = 1...
阅读全文
摘要:Reverse a linked list from positionmton. Do it in-place and in one-pass.For example:Given1->2->3->4->5->NULL,m= 2 andn= 4,return1->4->3->2->5->NULL.Note:Givenm,nsatisfy the following condition:1 ≤m≤n≤ length of list.ref:http://www.cnblogs.com/feiling/p/3263501.html添加一个s
阅读全文
摘要:Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.Initially, all next pointers are set toNULL.N...
阅读全文
摘要:Follow up for problem "Populating Next Right Pointers in Each Node".What if the given tree could be any binary tree? Would your previous solution stil...
阅读全文
摘要: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.ref:http://fisherlei.blogspot.com/2013/01/leetcode-rotate-list.html首先从head开始跑,直到最后一个节点,这时可以得出链表长度len。然后将尾指针指向头指针,将整个圈连起来,接着往前
阅读全文
摘要: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 =...
阅读全文
摘要:The gray code is a binary numeral system where two successive values differ in only one bit.Given a non-negative integernrepresenting the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.For example, givenn= 2, return[0,1,3,2]. Its gray code s
阅读全文
摘要:Given a collection of integers that might contain duplicates,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,2], a solution is:[ [2], [1], [1,2,2], [2,2], [1,2], []]解题思路: 跟subset 基...
阅读全文
摘要: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]. 1 public class Solution { 2 public int removeDuplicates(int[] A) { 3 if(A == null || A.length == 0)
阅读全文
摘要: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 quadruplets. .
阅读全文
摘要:Given an array of words and a lengthL, format the text such that each line has exactlyLcharacters and is fully (left and right) justified.You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces' 'when necessary so that each line
阅读全文
摘要: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 of inte
阅读全文
摘要:Given inorder and postorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree.后续遍历 根节点在最后一个元...
阅读全文
摘要:Given preorder and inorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree.ref:http://fish...
阅读全文
摘要:Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).For example,S="ADOBECODEBANC"T="ABC"Minimum window is"BANC".Note:If there is no such window in S that covers all characters in T, return the emtpy
阅读全文
摘要:Given an array withnobjects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.Note:You are not suppose to use the l
阅读全文
摘要:Given a string containing only digits, restore it by returning all possible valid IP address combinations.For example:Given"25525511135",return["255.255.11.135", "255.255.111.35"]. (Order does not matter)ref:http://www.cnblogs.com/feiling/p/3301869.htmlpublic static Arr
阅读全文
摘要:Given a linked list and a valuex, partition it such that all nodes less thanxcome before nodes greater than or equal tox.You should preserve the original relative order of the nodes in each of the two partitions.For example,Given1->4->3->2->5->2andx= 3,return1->2->2->4->3-
阅读全文
摘要:Given a matrix ofmxnelements (mrows,ncolumns), return all elements of the matrix in spiral order.For example,Given the following matrix:[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]You should return[1,2,3,6,9,8,7,4,5].相当于一圈一圈的剥掉矩阵,剥掉一圈,row-2, col-2 1 public class Solution { 2 public ArrayList spiralO...
阅读全文
摘要:Given a stringS, find the longest palindromic substring inS. You may assume that the maximum length ofSis 1000, and there exists one unique longest palindromic substring.参考:水中的鱼: [LeetCode]Longest Palindromic Substring解题报告定义函数P[i,j] = 字符串区间[i,j]是否为palindrome.首先找个例子,比如S="abccb", S= a b c c
阅读全文
摘要: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 → 0参考 :http://www.cnb
阅读全文
摘要:Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinctnumbers from the original list.For example,Given1->2->3->3->4->4->5, return1->2->5.Given1->1->1->2->3, return2->3.解题思路 : 建立 fake noed 加在head 前面。cur = head; 比较cur 和 cur
阅读全文
摘要: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:[ [1, 3, ...
阅读全文
摘要:You are given annxn2D matrix representing an image.Rotate the image by 90 degrees (clockwise).Follow up:Could you do this in-place?参考:水中的鱼: [LeetCode]Rotate Image解题报告[解题思路]如下图,首先沿逆对角线翻转一次,然后按x轴中线翻转一次。 1 public class Solution { 2 public void rotate(int[][] matrix) { 3 if(matrix.length == ...
阅读全文
摘要:Given a collection of numbers that might contain duplicates, return all possible unique permutations.For example,[1,1,2]have the following unique permutations:[1,1,2],[1,2,1], and[2,1,1].参考:水中的鱼: [LeetCode]Permutations II解题报告[解题思路]跟 Permutations的解法一样,就是要考虑“去重”。先对数组进行排序,这样在DFS的时候,可以先判断前面的一个数是否和自己相等,相
阅读全文
摘要:Follow up for N-Queens problem.Now, instead outputting board configurations, return the total number of distinct solutions.跟N-Queens 一个解发 最后return result.size()public class Solution{ public ArrayList solveNQueens(int n) { ArrayList result = new ArrayList(); int[] queenList = new...
阅读全文
posted @ 2014-02-07 07:54
Razer.Lu
摘要:Determine whether an integer is a palindrome. Do this without extra space.Some hints:Could negative integers be palindromes? (ie, -1)If you are thinking of converting the integer to string, note the restriction of using extra space.You could also try reversing an integer. However, if you have solved
阅读全文
摘要: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.二维DP。设数组A[row][col],Min[i][j] = min(Min[i-1][j], Min[i][j-1]) +A[i][j];注意初始条件即可。public class
阅读全文
摘要: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], [0,1,
阅读全文
摘要: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.Your goal is to reach the last index in the minimum number of jumps.For example:Given array A =[2,3,1,1,4]The minimum n
阅读全文
摘要: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], returnfalse. 1
阅读全文
摘要:public class Solution { public int removeDuplicates(int[] A) { if(A.length == 0) return 0; int count = 1; for(int i = 1; i < A.length; i++){ if(A[i-1] == A[i]) continue; A[count++] = A[i]; ...
阅读全文
摘要:Convert Sorted Array to Binary Search TreeGiven an array where elements are sorted in ascending order, convert it to a height balanced BST./** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */pub...
阅读全文
摘要:Find the contiguous subarray within an array (containing at least one number) which has the largest sum.For example, given the array[−2,1,−3,4,−1,2,1,−5,4],the contiguous subarray[4,−1,2,1]has the largest sum =6.click to show more practice.More practice:If you have figured out the O(n) solution, try
阅读全文
摘要:Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inCwhere the candidate numbers sums toT.Each number inCmay only be usedoncein the combination.Note:All numbers (including target) will be positive integers.Elements in a combination (a1,a2, … ,ak) must
阅读全文
摘要: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,a2, … ,ak
阅读全文
摘要:Write a program to solve a Sudoku puzzle by filling the empty cells.Empty cells are indicated by the character'.'.You may assume that there will be only one unique solution.A sudoku puzzle......and its solution numbers marked in red. 1 public class Solution { 2 public void solveSudoku(char[]
阅读全文
摘要: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.rules:1. 同一行中1-9出现次数不重复2. 同一列中1-9出现次数不重复3. 9宫格中1-9出现次数不重复九宫格 block的顺序0 1 23 4 56 7 8
阅读全文
摘要: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 possible uni
阅读全文
摘要: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
阅读全文
摘要:Given a linked list, reverse the nodes of a linked listkat a time and return its modified list.If the number of nodes is not a multiple ofkthen left-out nodes in the end should remain as it is.You may not alter the values in the nodes, only nodes itself may be changed.Only constant memory is allowed
阅读全文
摘要: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 pass. 1
阅读全文
摘要:A message containing letters fromA-Zis being encoded to numbers using the following mapping:'A' -> 1'B' -> 2...'Z' -> 26Given an encoded message containing digits, determine the total number of ways to decode it.For example,Given encoded message"12", it cou
阅读全文
摘要:Given a strings, partitionssuch that every substring of the partition is a palindrome.Return the minimum cuts needed for a palindrome partitioning ofs.For example, givens="aab",Return1since the palindrome partitioning["aa","b"]could be produced using 1 cut.[Thoughts]凡是求
阅读全文
摘要:Given a 2D board containing'X'and'O', capture all regions surrounded by'X'.A region is captured by flipping all'O's into'X's in that surrounded region .For example,X X X XX O O XX X O XX O X XAfter running your function, the board should be:X X X XX X X XX X X
阅读全文
摘要:Given a strings, partitionssuch that every substring of the partition is a palindrome.Return all possible palindrome partitioning ofs.For example, givens="aab",Return [ ["aa","b"], ["a","a","b"] ]【解题思路】DFS 找到s的所有的substring, 判断是否是palindrome,
阅读全文
摘要:Reverse digits of an integer.Example1:x = 123, return 321Example2:x = -123, return -321Have you thought about this?Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!If the integer's last digit is 0, what should the output be? ie, cas
阅读全文
摘要:Given a 2D board and a word, find if the word exists in the grid.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.For example,Givenboard=[ [&q
阅读全文
摘要: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], []][解题思路]这个就是排列组合中的排列问题。递归如下逻辑:F...
阅读全文
摘要:Given an unsorted array of integers, find the length of the longest consecutive elements sequence.For example,Given[100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.Your algorithm should run in O(n) complexity.[解题思路]数组,O(n)---->使用hash,空间换时间对于当前数N
阅读全文
摘要:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.Ref:http://www.cnblogs.com/feiling/p/3267...
阅读全文
摘要:DFS 1 public class Solution { 2 public ArrayList> combine(int n, int k) { 3 ArrayList> res = new ArrayList>(); 4 if(k == 0 || n == 0) 5 return res; 6 7 ArrayList output = new ArrayList(); 8 generate(1, n, k, output, res); 9 return ...
阅读全文
摘要:Given a stringsconsists of upper/lower-case alphabets and empty space characters' ', return the length of last word in the string.If the last word does not exist, return 0.Note:A word is defined as a character sequence consists of non-space characters only.For example,Givens="Hello Worl
阅读全文
摘要: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 rep...
阅读全文
摘要:[解题思路]记录下一层元素个数,这样每次遍历时就知道何时结束,只需一个queue用一个count来计数每一层的node的个数,/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public ArrayList> levelOrder(TreeNode root) { ...
阅读全文
摘要:[解题思路]二叉树的层序遍历通过使用queue来实现,上网搜索了下,发现该题可以使用栈来解决,通过分析执行结果确实是后进先出这里通过定义leftToRight来表示是从左到右还是从右到左从左到右:先加left后加right从右到左:先加right后加leftorderlevel traversal 遍历最后每行添加到result前 判断是leftToRight 还是Right to Left/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * Tr...
阅读全文
摘要:Given a binary tree, return theinordertraversal of its nodes' values.For example:Given binary tree{1,#,2,3}, 1 \ 2 / 3return[1,3,2].Note:Recursive solution is trivial, could you do it iteratively?Recursive Version/** * Definition for binary tree * public class TreeNode { * int val;...
阅读全文
摘要:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node./** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { v...
阅读全文

浙公网安备 33010602011771号