├── 20131127 Evaluate Reverse Polish Notation.cpp ├── README.md ├── 20120319 Pow(x, n).py ├── 20111225 Reverse Integer.py ├── 20120104 Palindrome Number.py ├── 20120403 Sqrt(x).py ├── 20140305 Reverse Words in a String.py ├── 20120403 Climbing Stairs.py ├── 20121028 Pascal's Triangle II.cpp ├── 20131001 Single Number.cpp ├── 20120115 Roman to Integer.py ├── 20120117 Longest Common Prefix.py ├── 20120402 Plus One.py ├── 20120216 Remove Element.py ├── 20120321 Maximum Subarray.py ├── 20120419 Remove Duplicates from Sorted Array II.py ├── 20120929 Maximum Depth of Binary Tree.cpp ├── 20120418 Subsets.py ├── 20121030 Best Time to Buy and Sell Stock I.cpp ├── 20121028 Pascal's.cpp ├── 20120320 N-Queens II.py ├── 20120130 Valid Parentheses.py ├── 20120327 Length of Last Word.py ├── 20120328 Unique Paths.py ├── 20131002 Single Number II.cpp ├── 20120903 Same Tree.cpp ├── 20131028 Linked List Cycle.cpp ├── 20120108 Container With Most Water.py ├── 20120319 Anagrams.py ├── 20120218 Divide Two Integers.py ├── 20131105 Binary Tree Preorder Traversal.cpp ├── 20120520 Gray Code.py ├── 20120308 First Missing Positive.py ├── 20120324 Jump Game.py ├── 20120115 Integer to Roman.py ├── 20120303 Search Insert Position.py ├── 20120317 Rotate Image.py ├── 20120418 Combinations.py ├── 20111226 String to Integer (atoi).py ├── 20120328 Minimum Path Sum.py ├── 20121030 Best Time to Buy and Sell Stock II.cpp ├── 20120520 Merge Sorted Array.py ├── 20120316 Jump Game II.py ├── 20110313 Two Sum.py ├── 20121009 Minimum Depth of Binary Tree.cpp ├── 20120127 Remove Nth Node From End of List.py ├── 20120327 Spiral Matrix II.py ├── 20121002 Convert Sorted Array to Binary Search Tree.cpp ├── 20110515 Longest Substring Without Repeating Characters.py ├── 20121029 Triangle.cpp ├── 20131030 Linked List Cycle II.cpp ├── 20120303 Valid Sudoku.py ├── 20120312 Multiply Strings.py ├── 20120827 Unique Binary Search Trees.cpp ├── 20120402 Add Binary.py ├── 20120212 Generate Parentheses.py ├── 20120302 Search in Rotated Sorted Array.py ├── 20120126 Letter Combinations of a Phone Number.py ├── 20120305 Count and Say.py ├── 20120419 Search in Rotated Sorted Array II.py ├── 20120310 Trapping Rain Water.py ├── 20120327 Permutation Sequence.py ├── 20120625 Subsets II.py ├── 20120118 3Sum Closest.py ├── 20120625 Decode Ways.py ├── 20120229 Longest Valid Parentheses.py ├── 20121008 Balanced Binary Tree.cpp ├── 20111111 Longest Palindromic Substring.py ├── 20121106 Best Time to Buy and Sell Stock III.cpp ├── 20130112 Valid Palindrome.cpp ├── 20120422 Remove Duplicates from Sorted List.py ├── 20120830 Interleaving String.py ├── 20121107 Binary Tree Maximum Path Sum.cpp ├── 20121018 Distinct Subsequences.cpp ├── 20120316 Permutations.py ├── 20120422 Largest Rectangle in Histogram.py ├── 20131107 Binary Tree Postorder Traversal.cpp ├── 20120218 Implement strStr().py ├── 20120327 Rotate List.py ├── 20120316 Permutations II.py ├── 20120330 Merge Two Sorted Lists.py ├── 20120404 Edit Distance.py ├── 20130928 Gas Station.cpp ├── 20120324 Spiral Matrix.py ├── 20130228 Palindrome Partitioning II.cpp ├── 20120406 Search a 2D Matrix.py ├── 20120326 Merge Intervals.py ├── 20120827 Binary Tree Inorder Traversal.cpp ├── 20110327 Median of Two Sorted Arrays.py ├── 20120423 Maximal Rectangle.py ├── 20120807 Restore IP Addresses.cpp ├── 20130213 Longest Consecutive Sequence.cpp ├── 20131004 Word Break.cpp ├── 20131112 Insertion Sort List.cpp ├── 20120216 Remove Duplicates from Sorted Array.py ├── 20131102 Reorder List.cpp ├── 20120319 N-Queens.py ├── 20111205 ZigZag Conversion.py ├── 20120930 Construct Binary Tree from Preorder and Inorder Traversal.cpp ├── 20120930 Construct Binary Tree from Inorder and Postorder Traversal.cpp ├── 20120117 3Sum.py ├── 20120225 Next Permutation.py ├── 20120328 Unique Paths II.py ├── 20121013 Path Sum.cpp ├── 20131122 Max Points on a Line.cpp ├── 20121002 Convert Sorted List to Binary Search Tree.cpp ├── 20120928 Binary Tree Level Order Traversal.cpp ├── 20121001 Binary Tree Level Order Traversal II.cpp ├── 20120831 Validate Binary Search Tree.py ├── 20131003 Copy List with Random Pointer.cpp ├── 20111101 Add Two Numbers.py ├── 20120422 Remove Duplicates from Sorted List II.py ├── 20120901 Recover Binary Search Tree.py ├── 20120306 Combination Sum.py ├── 20120430 Partition List.py ├── 20120302 Search for a Range.py ├── 20120408 Sort Colors.py ├── 20120214 Swap Nodes in Pairs.py ├── 20130218 Sum Root to Leaf Numbers.cpp ├── 20120928 Binary Tree Zigzag Level Order Traversal.cpp ├── 20121014 Flatten Binary Tree to Linked List.cpp ├── 20120315 Wildcard Matching.py ├── 20120403 Simplify Path.cpp ├── 20120827 Unique Binary Search Trees II.py ├── 20120415 Minimum Window Substring.py ├── 20130930 Candy.cpp ├── 20120627 Reverse Linked List II.py ├── 20120405 Set Matrix Zeroes.py ├── 20121028 Populating Next Right Pointers in Each Node.cpp ├── 20120306 Combination Sum II.py ├── 20131116 Sort List.cpp ├── 20120923 Symmetric Tree.cpp ├── 20130227 Palindrome Partitioning.cpp ├── 20121014 Path Sum II.cpp ├── 20120418 Word Search.py ├── 20130210 Word Ladder.cpp ├── 20120126 4Sum.cpp ├── 20120327 Insert Interval.py ├── 20130221 Surrounded Regions.cpp ├── 20131109 LRU Cache.cpp ├── 20120304 Sudoku Solver.py ├── 20120402 Valid Number.py ├── 20121028 Populating Next Right Pointers in Each Node II.cpp ├── 20120108 Regular Expression Matching.py ├── 20120223 Substring with Concatenation of All Words.py ├── 20120213 Merge k Sorted Lists.py ├── 20120215 Reverse Nodes in k-Group.py ├── 20120430 Scramble String.py ├── 20131005 Word Break II.cpp ├── 20130924 Clone Graph.cpp ├── 20120403 Text Justification.py └── 20130210 Word Ladder II.cpp /20131127 Evaluate Reverse Polish Notation.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ##Solution for problems at oj.leetcode.com 2 | 3 | Solvint Report: 4 | [Part 1](https://swm8023.github.io/blog/2014/03/18/leetcode-solution-01/) 5 | [Part 2](https://swm8023.github.io/blog/2014/03/18/leetcode-solution-02/) 6 | -------------------------------------------------------------------------------- /20120319 Pow(x, n).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement pow(x, n). 3 | ''' 4 | class Solution: 5 | # @param x, a float 6 | # @param n, a integer 7 | # @return a float 8 | def pow(self, x, n): 9 | if n == 0: 10 | return 1 11 | xx = pow(x, n >> 1) 12 | xx *= xx 13 | if n & 1: xx *= x 14 | return xx -------------------------------------------------------------------------------- /20111225 Reverse Integer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Reverse digits of an integer. 3 | 4 | Example1: x = 123, return 321 5 | Example2: x = -123, return -321 6 | ''' 7 | class Solution: 8 | # @return an integer 9 | def reverse(self, x): 10 | a = 0 11 | b = x if x > 0 else -x 12 | while b: 13 | a, b = a * 10 + b % 10, b / 10 14 | return a if x > 0 else -a -------------------------------------------------------------------------------- /20120104 Palindrome Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Determine whether an integer is a palindrome. Do this without extra space. 3 | ''' 4 | 5 | class Solution: 6 | # @return a boolean 7 | def isPalindrome(self, x): 8 | if x <= 0: 9 | return False if x < 0 else True 10 | a, b = x, 0 11 | while a: 12 | b, a = b * 10 + a % 10, a / 10 13 | return b == x -------------------------------------------------------------------------------- /20120403 Sqrt(x).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement int sqrt(int x). 3 | 4 | Compute and return the square root of x. 5 | ''' 6 | 7 | class Solution: 8 | # @param x, an integer 9 | # @return an integer 10 | def sqrt(self, x): 11 | y0, y1 = 0, 1 12 | while int(y0) != int(y1): 13 | y0 = y1 14 | y1 = 1.0/2.0 * (y0 + x / y0) 15 | return int(y0) 16 | 17 | -------------------------------------------------------------------------------- /20140305 Reverse Words in a String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an input string, reverse the string word by word. 3 | 4 | For example, 5 | Given s = "the sky is blue", 6 | return "blue is sky the". 7 | ''' 8 | class Solution: 9 | # @param s, a string 10 | # @return a string 11 | def reverseWords(self, s): 12 | return ' '.join([word[::-1] for word in s[::-1].split()]) 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /20120403 Climbing Stairs.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are climbing a stair case. It takes n steps to reach to the top. 3 | 4 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | ''' 6 | 7 | class Solution: 8 | # @param n, an integer 9 | # @return an integer 10 | def climbStairs(self, n): 11 | f = [1, 1] 12 | while len(f) <= n: 13 | f.append(f[-1] + f[-2]) 14 | return f[n] -------------------------------------------------------------------------------- /20121028 Pascal's Triangle II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an index k, return the kth row of the Pascal's triangle. 3 | 4 | For example, given k = 3, 5 | Return [1,3,3,1]. 6 | 7 | Note: 8 | Could you optimize your algorithm to use only O(k) extra space? 9 | 10 | */ 11 | class Solution { 12 | public: 13 | vector ans; 14 | vector getRow(int rowIndex) { 15 | ans.resize(rowIndex + 1); 16 | ans[0] = 1; 17 | for (int i = 1; i <= rowIndex; i++) 18 | ans[i] = (long long)ans[i-1] * (rowIndex - i + 1) / i; 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /20131001 Single Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, every element appears twice except for one. Find that single one. 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | */ 7 | class Solution { 8 | public: 9 | int singleNumber(int A[], int n) { 10 | // IMPORTANT: Please reset any member data you declared, as 11 | // the same Solution instance will be reused for each test case. 12 | int x = 0; 13 | while (--n >= 0) x ^= A[n]; 14 | return x; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /20120115 Roman to Integer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a roman numeral, convert it to an integer. 3 | 4 | Input is guaranteed to be within the range from 1 to 3999. 5 | ''' 6 | 7 | class Solution: 8 | # @return an integer 9 | def romanToInt(self, s): 10 | roval = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} 11 | ans = 0 12 | for i in range(len(s)): 13 | if i + 1 < len(s) and roval[s[i]] < roval[s[i+1]]: 14 | ans -= roval[s[i]] 15 | else: 16 | ans += roval[s[i]] 17 | return ans 18 | -------------------------------------------------------------------------------- /20120117 Longest Common Prefix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | ''' 4 | class Solution: 5 | # @return a string 6 | def longestCommonPrefix(self, strs): 7 | if len(strs) <= 1: 8 | return strs[0] if len(strs) == 1 else "" 9 | end, minl = 0, min([len(s) for s in strs]) 10 | while end < minl: 11 | for i in range(1, len(strs)): 12 | if strs[i][end] != strs[i-1][end]: 13 | return strs[0][:end] 14 | end = end + 1 15 | return strs[0][:end] -------------------------------------------------------------------------------- /20120402 Plus One.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-negative number represented as an array of digits, plus one to the number. 3 | 4 | The digits are stored such that the most significant digit is at the head of the list. 5 | ''' 6 | 7 | class Solution: 8 | # @param digits, a list of integer digits 9 | # @return a list of integer digits 10 | def plusOne(self, digits): 11 | for i in range(len(digits)-1, -1, -1): 12 | digits[i] = (digits[i] + 1) % 10 13 | if digits[i]: 14 | break; 15 | else: 16 | digits.insert(0, 1) 17 | return digits 18 | -------------------------------------------------------------------------------- /20120216 Remove Element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array and a value, remove all instances of that value in place and return the new length. 3 | 4 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 5 | ''' 6 | 7 | class Solution: 8 | # @param A a list of integers 9 | # @param elem an integer, value need to be removed 10 | # @return an integer 11 | def removeElement(self, A, elem): 12 | sz = 0 13 | for i in range(0, len(A)): 14 | if A[i] != elem: 15 | A[sz] = A[i] 16 | sz += 1 17 | return sz -------------------------------------------------------------------------------- /20120321 Maximum Subarray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 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 | 7 | class Solution: 8 | # @param A, a list of integers 9 | # @return an integer 10 | def maxSubArray(self, A): 11 | ans, sum = A[0], A[0] 12 | for i in range(1, len(A)): 13 | if (sum < 0): 14 | sum = A[i] 15 | else: 16 | sum += A[i] 17 | ans = max(ans, sum) 18 | return ans 19 | -------------------------------------------------------------------------------- /20120419 Remove Duplicates from Sorted Array II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Follow up for "Remove Duplicates": 3 | What if duplicates are allowed at most twice? 4 | 5 | For example, 6 | Given sorted array A = [1,1,1,2,2,3], 7 | 8 | Your function should return length = 5, and A is now [1,1,2,2,3]. 9 | ''' 10 | 11 | class Solution: 12 | # @param A a list of integers 13 | # @return an integer 14 | def removeDuplicates(self, A): 15 | i = 2; 16 | while i < len(A): 17 | if A[i] == A[i-1] and A[i] == A[i - 2]: 18 | A.pop(i) 19 | else: 20 | i = i + 1 21 | return len(A) 22 | -------------------------------------------------------------------------------- /20120929 Maximum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 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 | * Definition for binary tree 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | int maxDepth(TreeNode *root) { 18 | if (root == NULL) return 0; 19 | return 1 + max(maxDepth(root->left), maxDepth(root->right)); 20 | } 21 | 22 | }; -------------------------------------------------------------------------------- /20120418 Subsets.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a set of distinct integers, S, return all possible subsets. 3 | 4 | Note: 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 | class Solution: 22 | # @param S, a list of integer 23 | # @return a list of lists of integer 24 | def subsets(self, S): 25 | S.sort() 26 | return [[S[x] for x in range(len(S)) if i>>x&1] for i in range(2**len(S))] 27 | -------------------------------------------------------------------------------- /20121030 Best Time to Buy and Sell Stock I.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | 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. 5 | */ 6 | class Solution { 7 | public: 8 | int maxProfit(vector &prices) { 9 | if (prices.size() == 0) return 0; 10 | int ans = 0, minv = prices[0]; 11 | for (int i = 1; i < prices.size(); i++) { 12 | ans = max(ans, prices[i] - minv); 13 | minv = min(minv, prices[i]); 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /20121028 Pascal's.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given numRows, generate the first numRows of Pascal's triangle. 3 | 4 | For example, given numRows = 5, 5 | Return 6 | 7 | [ 8 | [1], 9 | [1,1], 10 | [1,2,1], 11 | [1,3,3,1], 12 | [1,4,6,4,1] 13 | ] 14 | 15 | */ 16 | class Solution { 17 | public: 18 | vector > ans; 19 | vector > generate(int numRows) { 20 | ans.clear(); 21 | ans.resize(numRows); 22 | for (int i = 0; i < numRows ;i++) { 23 | ans[i].resize(i+1); 24 | ans[i][0] = ans[i][i] = 1; 25 | for (int j = 1; j < i; j++) 26 | ans[i][j] = ans[i-1][j-1] + ans[i-1][j]; 27 | } 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /20120320 N-Queens II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Follow up for N-Queens problem. 3 | 4 | Now, instead outputting board configurations, return the total number of distinct solutions. 5 | ''' 6 | 7 | class Solution: 8 | # @return an integer 9 | def totalNQueens(self, n): 10 | self.ans = 0 11 | self.full = ((1 << n) - 1) 12 | self.dfs(n, 0, 0, 0, 0) 13 | return self.ans 14 | 15 | def dfs(self, n, p, lt, rt, nt): 16 | if n == p: 17 | self.ans += 1 18 | return 19 | can = (~(lt | rt | nt) & self.full) 20 | while can: 21 | now = can&-can 22 | self.dfs(n, p+1, (lt|now)>>1, (rt|now)<<1, nt|now) 23 | can -= now 24 | -------------------------------------------------------------------------------- /20120130 Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 5 | ''' 6 | 7 | class Solution: 8 | # @return a boolean 9 | def isValid(self, s): 10 | dct = {'(':')', '[':']', '{':'}'} 11 | stk = [] 12 | for c in s: 13 | if dct.get(c, None): 14 | stk.append(c) 15 | elif len(stk) == 0 or dct[stk[-1]] != c: 16 | return False 17 | else: 18 | stk.pop() 19 | return True if len(stk) == 0 else False 20 | -------------------------------------------------------------------------------- /20120327 Length of Last Word.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 3 | 4 | If the last word does not exist, return 0. 5 | 6 | Note: A word is defined as a character sequence consists of non-space characters only. 7 | 8 | For example, 9 | Given s = "Hello World", 10 | return 5. 11 | ''' 12 | 13 | class Solution: 14 | # @param s, a string 15 | # @return an integer 16 | def lengthOfLastWord(self, s): 17 | i = len(s) - 1 18 | while i >= 0 and s[i] == ' ': i -= 1 19 | j = i - 1 20 | while j >= 0 and s[j] != ' ': j -= 1 21 | return 0 if i < 0 else i - j 22 | 23 | 24 | -------------------------------------------------------------------------------- /20120328 Unique Paths.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 3 | 4 | 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). 5 | 6 | How many possible unique paths are there? 7 | ''' 8 | 9 | class Solution: 10 | # @return an integer 11 | def uniquePaths(self, m, n): 12 | g = [[0] * n for i in range(m)] 13 | for i in range(m): g[i][0] = 1 14 | for j in range(n): g[0][j] = 1 15 | for i in range(1, m): 16 | for j in range(1, n): 17 | g[i][j] = g[i][j-1] + g[i-1][j] 18 | return g[m-1][n-1] -------------------------------------------------------------------------------- /20131002 Single Number II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, every element appears three times except for one. Find that single one. 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | */ 7 | class Solution { 8 | public: 9 | int singleNumber(int A[], int n) { 10 | // IMPORTANT: Please reset any member data you declared, as 11 | // the same Solution instance will be reused for each test case. 12 | int x[3] = {0}; 13 | while (--n >= 0) { 14 | x[2] = x[1] & A[n]; 15 | x[1] |= x[0] & A[n]; 16 | x[0] |= A[n]; 17 | x[0] &= ~x[2], x[1] &= ~x[2]; 18 | } 19 | return x[0]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /20120903 Same Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two binary trees, write a function to check if they are equal or not. 3 | 4 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 5 | */ 6 | /** 7 | * Definition for binary tree 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | bool isSameTree(TreeNode *p, TreeNode *q) { 18 | if (!p || !q) return !p && !q; 19 | if (p->val != q->val) return false; 20 | return isSameTree(p->left, q->left) && 21 | isSameTree(p->right, q->right); 22 | } 23 | }; -------------------------------------------------------------------------------- /20131028 Linked List Cycle.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | // IMPORTANT: Please reset any member data you declared, as 13 | // the same Solution instance will be reused for each test case. 14 | ListNode *h1, *h2; 15 | for(h1 = h2 = head; h1 && h2;){ 16 | if (!h1->next || !h2->next || !h2->next->next) 17 | return false; 18 | h1 = h1->next; 19 | h2 = h2->next->next; 20 | if (h1 == h2 && h1) return true; 21 | } 22 | return false; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /20120108 Container With Most Water.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | Note: You may not slant the container. 5 | ''' 6 | class Solution: 7 | # @return an integer 8 | def maxArea(self, height): 9 | l, r, ans = 0, len(height) - 1, 0 10 | while l <= r: 11 | ans = max(ans, (r - l) * min(height[r], height[l])) 12 | if height[l] < height[r]: 13 | l = l + 1 14 | else: 15 | r = r - 1 16 | return ans 17 | -------------------------------------------------------------------------------- /20120319 Anagrams.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of strings, return all groups of strings that are anagrams. 3 | 4 | Note: All inputs will be in lower-case. 5 | ''' 6 | 7 | class Solution: 8 | # @param strs, a list of strings 9 | # @return a list of strings 10 | def anagrams(self, strs): 11 | ans, dt = [], {} 12 | for i in range(len(strs)): 13 | lt = list(strs[i]) 14 | lt.sort() 15 | s = ''.join(lt) 16 | d = dt.get(s, -2) 17 | if d == -2: 18 | dt[s] = i 19 | elif d == -1: 20 | ans.append(strs[i]) 21 | else: 22 | ans.append(strs[i]) 23 | ans.append(strs[d]) 24 | dt[s] = -1 25 | return ans -------------------------------------------------------------------------------- /20120218 Divide Two Integers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Divide two integers without using multiplication, division and mod operator. 3 | ''' 4 | 5 | class Solution: 6 | # @return an integer 7 | def divide(self, dividend, divisor): 8 | flag, ans = 0, 0 9 | if dividend < 0: 10 | flag, dividend = flag^1, -dividend 11 | if divisor < 0: 12 | flag, divisor = flag^1, -divisor 13 | while dividend >= divisor: 14 | count, newDivisor = 1, divisor 15 | while newDivisor + newDivisor <= dividend: 16 | newDivisor = newDivisor + newDivisor 17 | count = count + count 18 | dividend -= newDivisor 19 | ans += count 20 | return ans if flag == 0 else -ans 21 | 22 | -------------------------------------------------------------------------------- /20131105 Binary Tree Preorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Solution { 5 | public: 6 | vector vec; 7 | vector preorderTraversal(TreeNode *root) { 8 | // IMPORTANT: Please reset any member data you declared, as 9 | // the same Solution instance will be reused for each test case. 10 | stack st; 11 | vec.clear(); 12 | TreeNode *T = root; 13 | while (T || !st.empty()) { 14 | if (T) { 15 | vec.push_back(T->val); 16 | st.push(T); 17 | T = T->left; 18 | } else { 19 | T = st.top(); st.pop(); 20 | T = T->right; 21 | } 22 | } 23 | return vec; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /20120520 Gray Code.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The gray code is a binary numeral system where two successive values differ in only one bit. 3 | 4 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 5 | 6 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 7 | 8 | 00 - 0 9 | 01 - 1 10 | 11 - 3 11 | 10 - 2 12 | ''' 13 | 14 | class Solution: 15 | # @return a list of integers 16 | def grayCode(self, n): 17 | self.res = [0] 18 | for i in [2**x for x in range(0, n)]: 19 | self.res.append(self.res[-1] + i) 20 | self.res.extend([i + v for v in self.res[-3:None:-1]]) 21 | return self.res; 22 | 23 | s = Solution() 24 | print s.grayCode(3) -------------------------------------------------------------------------------- /20120308 First Missing Positive.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted integer array, find the first missing positive integer. 3 | 4 | For example, 5 | Given [1,2,0] return 3, 6 | and [3,4,-1,1] return 2. 7 | 8 | Your algorithm should run in O(n) time and uses constant space. 9 | ''' 10 | 11 | class Solution: 12 | # @param A, a list of integers 13 | # @return an integer 14 | def firstMissingPositive(self, A): 15 | L = len(A) 16 | for i in range(L): 17 | while A[i] > 0 and A[i] <= L and A[i] != A[A[i] - 1] and i != A[i] - 1: 18 | A[A[i] - 1], A[i] = A[i], A[A[i] - 1] 19 | #A[i], A[A[i] - 1] = A[A[i] - 1], A[i] dosen't work 20 | for i in range(L): 21 | if i != A[i] - 1: 22 | return i + 1 23 | return L + 1 -------------------------------------------------------------------------------- /20120324 Jump Game.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Determine if you are able to reach the last index. 7 | 8 | For example: 9 | A = [2,3,1,1,4], return true. 10 | 11 | A = [3,2,1,0,4], return false. 12 | ''' 13 | 14 | class Solution: 15 | # @param A, a list of integers 16 | # @return a boolean 17 | def canJump(self, A): 18 | if len(A) == 0: 19 | return False 20 | maxj = A[0] 21 | for i in range(1, len(A)): 22 | maxj -= 1 23 | if (maxj < 0): 24 | return False 25 | maxj = max(maxj, A[i]) 26 | return True 27 | -------------------------------------------------------------------------------- /20120115 Integer to Roman.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer, convert it to a roman numeral. 3 | 4 | Input is guaranteed to be within the range from 1 to 3999. 5 | ''' 6 | class Solution: 7 | # @return a string 8 | def intToRoman(self, num): 9 | ronum = [['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'], 10 | ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'], 11 | ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'], 12 | ['', 'M', 'MM', 'MMM', ' ', ' ', ' ', ' ', ' ', ' ']] 13 | ans, ind = '', 0 14 | while num: 15 | ans = ronum[ind][num%10] + ans 16 | num, ind = num / 10, ind + 1 17 | return ans 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /20120303 Search Insert Position.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | You may assume no duplicates in the array. 5 | 6 | Here are few examples. 7 | [1,3,5,6], 5 -> 2 8 | [1,3,5,6], 2 -> 1 9 | [1,3,5,6], 7 -> 4 10 | [1,3,5,6], 0 -> 0 11 | ''' 12 | 13 | class Solution: 14 | # @param A, a list of integers 15 | # @param target, an integer to be inserted 16 | # @return integer 17 | def searchInsert(self, A, target): 18 | l, h = 0, len(A) 19 | while l < h: 20 | m = (l + h) // 2 21 | if A[m] < target: 22 | l = m + 1 23 | else: 24 | h = m 25 | return l 26 | 27 | -------------------------------------------------------------------------------- /20120317 Rotate Image.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an n x n 2D matrix representing an image. 3 | 4 | Rotate the image by 90 degrees (clockwise). 5 | 6 | Follow up: 7 | Could you do this in-place? 8 | ''' 9 | 10 | class Solution: 11 | # @param matrix, a list of lists of integers 12 | # @return a list of lists of integers 13 | def rotate(self, matrix): 14 | L = len(matrix) 15 | R = (L + 1) // 2 16 | for x in range(0, R): 17 | for y in range(0, L - R): 18 | #(x,y)->(y,l-1-x)->(l-1-x,l-1-y)->(l-1-y,x) 19 | matrix[x][y], matrix[y][L-1-x], matrix[L-1-x][L-1-y], matrix[L-1-y][x] \ 20 | = matrix[L-1-y][x], matrix[x][y], matrix[y][L-1-x], matrix[L-1-x][L-1-y] 21 | return matrix 22 | 23 | -------------------------------------------------------------------------------- /20120418 Combinations.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 3 | 4 | For example, 5 | If n = 4 and k = 2, a solution is: 6 | 7 | [ 8 | [2,4], 9 | [3,4], 10 | [2,3], 11 | [1,2], 12 | [1,3], 13 | [1,4], 14 | ] 15 | ''' 16 | 17 | class Solution: 18 | # @return a list of lists of integers 19 | def combine(self, n, k): 20 | self.res = [] 21 | tmp = [] 22 | self.dfs(n, k, 1, 0, tmp) 23 | return self.res 24 | 25 | def dfs(self, n, k, m, p, tmp): 26 | if k == p: 27 | self.res.append(tmp[:]) 28 | return 29 | for i in range(m, n+1): 30 | tmp.append(i) 31 | self.dfs(n, k, i+1, p+1, tmp) 32 | tmp.pop() 33 | 34 | -------------------------------------------------------------------------------- /20111226 String to Integer (atoi).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement atoi to convert a string to an integer. 3 | ''' 4 | 5 | class Solution: 6 | # @return an integer 7 | def atoi(self, str): 8 | if len(str) == 0: 9 | return 0 10 | sgn, num, p = 0, 0, 0 11 | imin, imax = -1<<31, (1<<31)-1 12 | while str[p] == ' ': 13 | p = p + 1 14 | if str[p] == '-' or str[p] == '+': 15 | sgn = 1 if str[p] == '-' else 0 16 | p = p + 1 17 | while p < len(str) and str[p] >= '0' and str[p] <= '9': 18 | num = num * 10 + ord(str[p]) - ord('0') 19 | x = -num if sgn else num 20 | if x < imin: return imin 21 | if x > imax: return imax 22 | p = p + 1 23 | return -num if sgn else num 24 | 25 | -------------------------------------------------------------------------------- /20120328 Minimum Path Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | Note: You can only move either down or right at any point in time. 5 | ''' 6 | 7 | class Solution: 8 | # @param grid, a list of lists of integers 9 | # @return an integer 10 | def minPathSum(self, grid): 11 | for i in range(len(grid)): 12 | for j in range(len(grid[0])): 13 | if i == 0 and j > 0: 14 | grid[i][j] += grid[i][j-1] 15 | elif j == 0 and i > 0: 16 | grid[i][j] += grid[i-1][j] 17 | elif i > 0 and j > 0: 18 | grid[i][j] += min(grid[i-1][j], grid[i][j-1]) 19 | return grid[len(grid) - 1][len(grid[0]) - 1] -------------------------------------------------------------------------------- /20121030 Best Time to Buy and Sell Stock II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | 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 transactions at the same time (ie, you must sell the stock before you buy again). 5 | */ 6 | class Solution { 7 | public: 8 | int maxProfit(vector &prices) { 9 | if (prices.size() == 0) return 0; 10 | int minv = prices[0], ans = 0; 11 | for (int i = 1; i < prices.size(); i++) { 12 | if (prices[i] > minv) 13 | ans += prices[i] - minv, minv = prices[i]; 14 | minv = min(minv, prices[i]); 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /20120520 Merge Sorted Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two sorted integer arrays A and B, merge B into A as one sorted array. 3 | 4 | Note: 5 | You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. 6 | ''' 7 | class Solution: 8 | # @param A a list of integers 9 | # @param m an integer, length of A 10 | # @param B a list of integers 11 | # @param n an integer, length of B 12 | # @return nothing 13 | def merge(self, A, m, B, n): 14 | for i in range(m + n - 1, -1, -1): 15 | if m == 0 or (n > 0 and B[n-1] > A[m-1]): 16 | A[i] = B[n-1] 17 | n -= 1 18 | else: 19 | A[i] = A[m-1] 20 | m -= 1 21 | return A -------------------------------------------------------------------------------- /20120316 Jump Game II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Your goal is to reach the last index in the minimum number of jumps. 7 | 8 | For example: 9 | Given array A = [2,3,1,1,4] 10 | 11 | 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.) 12 | ''' 13 | 14 | class Solution: 15 | # @param A, a list of integers 16 | # @return an integer 17 | def jump(self, A): 18 | maxj, maxn, tms = 0, 0, 0 19 | for i in range(len(A) - 1): 20 | maxn = max(maxn, A[i] + i) 21 | if i == maxj: 22 | maxj, tms = maxn, tms + 1 23 | return tms 24 | 25 | -------------------------------------------------------------------------------- /20110313 Two Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, find two numbers such that they add up to a specific target number. 3 | 4 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 5 | 6 | You may assume that each input would have exactly one solution. 7 | 8 | Input: numbers={2, 7, 11, 15}, target=9 9 | Output: index1=1, index2=2 10 | ''' 11 | 12 | class Solution: 13 | # @return a tuple, (index1, index2) 14 | def twoSum(self, num, target): 15 | dict = {} 16 | for i in range(len(num)): 17 | if dict.get(target-num[i], None) == None: 18 | dict[num[i]] = i 19 | else: 20 | return (dict[target-num[i]] + 1, i + 1) 21 | 22 | -------------------------------------------------------------------------------- /20121009 Minimum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, find its minimum depth. 3 | 4 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | */ 6 | /** 7 | * Definition for binary tree 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | int minDepth(TreeNode *root) { 18 | if (!root) return 0; 19 | if (!root->left && !root->right) return 1; 20 | int ltval = -1, rtval = -1; 21 | if (root->left) ltval = minDepth(root->left); 22 | if (root->right) rtval = minDepth(root->right); 23 | return 1+ (ltval == -1 ? rtval : (rtval == -1 ? ltval : min(ltval, rtval))); 24 | } 25 | }; -------------------------------------------------------------------------------- /20120127 Remove Nth Node From End of List.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | 6 | ''' 7 | Given a linked list, remove the nth node from the end of list and return its head. 8 | ''' 9 | 10 | # Definition for singly-linked list. 11 | # class ListNode: 12 | # def __init__(self, x): 13 | # self.val = x 14 | # self.next = None 15 | 16 | class Solution: 17 | # @return a ListNode 18 | def removeNthFromEnd(self, head, n): 19 | nHead = ListNode(0) 20 | nHead.next = head 21 | p, t = 0, head 22 | while p < n: 23 | t = t.next 24 | p += 1 25 | pre = nHead 26 | while t: 27 | t, pre = t.next, pre.next 28 | pre.next = pre.next.next 29 | return nHead.next 30 | 31 | 32 | -------------------------------------------------------------------------------- /20120327 Spiral Matrix II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 3 | 4 | For example, 5 | Given n = 3, 6 | 7 | You should return the following matrix: 8 | [ 9 | [ 1, 2, 3 ], 10 | [ 8, 9, 4 ], 11 | [ 7, 6, 5 ] 12 | ] 13 | ''' 14 | 15 | class Solution: 16 | # @return a list of lists of integer 17 | def generateMatrix(self, n): 18 | a = [[0] * n for i in range(n)] 19 | sx, sy = 0, 0 20 | dx, dy, dn = [0, 1, 0, -1], [1, 0, -1, 0], 0 21 | for i in range(n * n): 22 | a[sx][sy] = i + 1 23 | nx, ny = sx + dx[dn], sy + dy[dn] 24 | if nx < 0 or nx < 0 or nx >= n or ny >= n or a[nx][ny]: 25 | dn = (dn + 1) % 4 26 | nx, ny = sx + dx[dn], sy + dy[dn] 27 | sx, sy = nx, ny 28 | return a 29 | -------------------------------------------------------------------------------- /20121002 Convert Sorted Array to Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | */ 4 | /** 5 | * Definition for binary tree 6 | * struct TreeNode { 7 | * int val; 8 | * TreeNode *left; 9 | * TreeNode *right; 10 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | TreeNode *sortedArrayToBST(vector &num) { 16 | return dfs(0, num.size()-1, num); 17 | } 18 | TreeNode *dfs(int left, int right, vector &num) { 19 | if (left > right) return NULL; 20 | int mid = (left + right) >> 1; 21 | TreeNode *node = new TreeNode(num[mid]); 22 | node->left = dfs(left, mid-1, num); 23 | node->right = dfs(mid+1, right, num); 24 | return node; 25 | } 26 | }; -------------------------------------------------------------------------------- /20110515 Longest Substring Without Repeating Characters.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | ''' 4 | class Solution: 5 | # @return an integer 6 | def lengthOfLongestSubstring(self, s): 7 | dict, ans, p1, p2 = {}, 0, 0, 0 8 | while p2 < len(s): 9 | p = dict.get(s[p2], None) 10 | if p == None: 11 | dict[s[p2]] = p2 12 | p2 += 1 13 | ans = max(ans, p2 - p1) 14 | else: 15 | while p1 <= p: 16 | dict.pop(s[p1]) 17 | p1 += 1 18 | p1 = p + 1 19 | return ans 20 | 21 | 22 | -------------------------------------------------------------------------------- /20121029 Triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 3 | 4 | For example, given the following triangle 5 | [ 6 | [2], 7 | [3,4], 8 | [6,5,7], 9 | [4,1,8,3] 10 | ] 11 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 12 | 13 | Note: 14 | Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 15 | */ 16 | class Solution { 17 | public: 18 | int minimumTotal(vector > &triangle) { 19 | int size = triangle.size(); 20 | vector ans(triangle[size-1]); 21 | for (int i = size-2; i >= 0; i--) { 22 | for (int j = 0; j <= i; j++) 23 | ans[j] = triangle[i][j] + min(ans[j], ans[j+1]); 24 | } 25 | return ans[0]; 26 | } 27 | }; 28 | 29 | -------------------------------------------------------------------------------- /20131030 Linked List Cycle II.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *detectCycle(ListNode *head) { 12 | // IMPORTANT: Please reset any member data you declared, as 13 | // the same Solution instance will be reused for each test case. 14 | ListNode *h1, *h2; 15 | for(h1 = h2 = head; h1 && h2;){ 16 | if (!h1->next || !h2->next || !h2->next->next) 17 | return false; 18 | h1 = h1->next; 19 | h2 = h2->next->next; 20 | if (h1 == h2 && h1) break; 21 | } 22 | if (!h1 || !h2) return NULL; 23 | h2 = head; 24 | while(h1 != h2) h1 = h1->next, h2 = h2->next; 25 | return h1; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /20120303 Valid Sudoku.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. 3 | 4 | The Sudoku board could be partially filled, where empty cells are filled with the character '.'. 5 | ''' 6 | 7 | class Solution: 8 | # @param board, a 9x9 2D array 9 | # @return a boolean 10 | def isValidSudoku(self, board): 11 | lt, rt, bt = [0] * 9, [0] * 9, [0] * 9 12 | for i in range(9): 13 | for j in range(9): 14 | print i, j 15 | if (board[i][j] == '.'): 16 | continue; 17 | num = ord(board[i][j]) - ord('1') 18 | if 0 == (~(lt[i]|rt[j]|bt[j/3*3+i/3]) & (1< 1 and ans[len(ans) - 1] == 0: 20 | ans.pop() 21 | return ''.join([chr(i + ord('0')) for i in ans][::-1]) 22 | -------------------------------------------------------------------------------- /20120827 Unique Binary Search Trees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 3 | 4 | For example, 5 | Given n = 3, there are a total of 5 unique BST's. 6 | 7 | 1 3 3 2 1 8 | \ / / / \ \ 9 | 3 2 1 1 3 2 10 | / / \ \ 11 | 2 1 2 3 12 | */ 13 | 14 | class Solution { 15 | public: 16 | int numTrees(int n) { 17 | int *dp = new int[n+1]; 18 | for (int i = 0; i <= n; i++) 19 | dp[i] = (i <= 1 ? 1 : -1); 20 | return dpit(dp, n); 21 | } 22 | int dpit(int dp[], int n) { 23 | if (dp[n] != -1) return dp[n]; 24 | dp[n] = 0; 25 | for (int i = 0; i < n; i++) 26 | dp[n] += dpit(dp, i) * dpit(dp, n-i-1); 27 | return dp[n]; 28 | } 29 | }; -------------------------------------------------------------------------------- /20120402 Add Binary.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two binary strings, return their sum (also a binary string). 3 | 4 | For example, 5 | a = "11" 6 | b = "1" 7 | Return "100". 8 | ''' 9 | 10 | class Solution: 11 | # @param a, a string 12 | # @param b, a string 13 | # @return a string 14 | def addBinary(self, a, b): 15 | a = [ord(c) - ord('0') for c in a][::-1] 16 | b = [ord(c) - ord('0') for c in b][::-1] 17 | if (len(a) < len(b)): 18 | a, b = b, a 19 | flag = 0 20 | for i in range(len(a)): 21 | if (i < len(b)): 22 | a[i] += b[i] 23 | a[i] += flag 24 | flag = a[i] // 2 25 | a[i] %= 2 26 | if flag: 27 | a.append(1) 28 | return ''.join([chr(c + ord('0')) for c in a][::-1]) 29 | 30 | s = Solution() 31 | print s.addBinary("0", "0") 32 | 33 | -------------------------------------------------------------------------------- /20120212 Generate Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | 4 | For example, given n = 3, a solution set is: 5 | 6 | "((()))", "(()())", "(())()", "()(())", "()()()" 7 | ''' 8 | 9 | class Solution: 10 | # @param an integer 11 | # @return a list of string 12 | def generateParenthesis(self, n): 13 | self.ans, tmp = [], [] 14 | lb = 0 15 | self.dfs(lb, 0, n, tmp) 16 | return self.ans 17 | 18 | def dfs(self, lb, p, n, tmp): 19 | if p == n * 2: 20 | self.ans.append(''.join(tmp)) 21 | return 22 | if lb < n: 23 | tmp.append('(') 24 | self.dfs(lb + 1, p + 1, n, tmp) 25 | tmp.pop() 26 | if p - lb < lb: 27 | tmp.append(')') 28 | self.dfs(lb, p + 1, n, tmp) 29 | tmp.pop() 30 | -------------------------------------------------------------------------------- /20120302 Search in Rotated Sorted Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 3 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 4 | You are given a target value to search. If found in the array return its index, otherwise return -1. 5 | You may assume no duplicate exists in the array. 6 | ''' 7 | 8 | class Solution: 9 | # @param A, a list of integers 10 | # @param target, an integer to be searched 11 | # @return an integer 12 | def search(self, A, target): 13 | l, h = 0, len(A) - 1 14 | while (l <= h): 15 | m = l + ((h - l) >> 1) 16 | if A[m] == target: 17 | return m 18 | elif (A[m] > A[l] and target < A[m] and target >= A[l]) or (A[m] < A[l] and not (target <= A[h] and target > A[m])): 19 | h = m - 1 20 | else: 21 | l = m + 1 22 | return -1 23 | -------------------------------------------------------------------------------- /20120126 Letter Combinations of a Phone Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a digit string, return all possible letter combinations that the number could represent. 3 | A mapping of digit to letters (just like on the telephone buttons) is given below. 4 | ''' 5 | 6 | class Solution: 7 | # @return a list of strings, [s1, s2] 8 | def letterCombinations(self, digits): 9 | if len(digits) == 0: 10 | return [""] 11 | self.dglist = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] 12 | self.ans, tmp = [], [] 13 | self.dfs(digits, 0, tmp) 14 | return self.ans 15 | 16 | def dfs(self, digits, p, tmp): 17 | if (p == len(digits)): 18 | self.ans.append(''.join(tmp)) 19 | return 20 | for c in self.dglist[ord(digits[p]) - ord('0')]: 21 | tmp.append(c) 22 | self.dfs(digits, p + 1, tmp) 23 | tmp.pop() 24 | -------------------------------------------------------------------------------- /20120305 Count and Say.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The count-and-say sequence is the sequence of integers beginning as follows: 3 | 1, 11, 21, 1211, 111221, ... 4 | 5 | 1 is read off as "one 1" or 11. 6 | 11 is read off as "two 1s" or 21. 7 | 21 is read off as "one 2, then one 1" or 1211. 8 | Given an integer n, generate the nth sequence. 9 | 10 | Note: The sequence of integers will be represented as a string. 11 | ''' 12 | 13 | class Solution: 14 | # @return a string 15 | def countAndSay(self, n): 16 | s, now = [str(1), ''], 0 17 | for i in range(1, n): 18 | now, pre, tot = now^1, now, 0 19 | s[now], p = "", 0 20 | while p < len(s[pre]): 21 | tot, v, p = 1, s[pre][p], p + 1 22 | while p < len(s[pre]) and v == s[pre][p]: 23 | p += 1 24 | tot += 1 25 | s[now] += str(tot) + v 26 | return s[now] 27 | -------------------------------------------------------------------------------- /20120419 Search in Rotated Sorted Array II.py: -------------------------------------------------------------------------------- 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 | class Solution: 11 | # @param A a list of integers 12 | # @param target an integer 13 | # @return a boolean 14 | def search(self, A, target): 15 | l, h = 0, len(A) - 1 16 | while (l <= h): 17 | m = l + ((h - l) >> 1) 18 | if A[m] == target: 19 | return True 20 | if A[m] == A[l] and A[m] == A[h]: 21 | l, h = l + 1, h - 1 22 | elif (A[m] > A[l] and target < A[m] and target >= A[l]) or (A[m] < A[l] and not (target <= A[h] and target > A[m])): 23 | h = m - 1 24 | else: 25 | l = m + 1 26 | return False -------------------------------------------------------------------------------- /20120310 Trapping Rain Water.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | For example, 5 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 6 | ''' 7 | 8 | class Solution: 9 | # @param A, a list of integers 10 | # @return an integer 11 | def trap(self, A): 12 | maxl, maxr, maxv, ans = [], [], 0, 0 13 | for i in range(len(A)): 14 | if A[i] > maxv: maxv = A[i] 15 | maxl.append(maxv) 16 | maxv = 0 17 | for i in range(len(A)-1, -1, -1): 18 | if A[i] > maxv: maxv = A[i] 19 | maxr.append(maxv) 20 | for i in range(len(A)): 21 | minh = min(maxl[i], maxr[len(A) - i - 1]) - A[i] 22 | ans += minh if minh > 0 else 0 23 | return ans 24 | 25 | s = Solution() 26 | print s.trap([0,1,0,2,1,0,1,3,2,1,2,1]) 27 | -------------------------------------------------------------------------------- /20120327 Permutation Sequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The set [1,2,3,...,n] contains a total of n! unique permutations. 3 | By listing and labeling all of the permutations in order, 4 | We get the following sequence (ie, for n = 3): 5 | 6 | "123" 7 | "132" 8 | "213" 9 | "231" 10 | "312" 11 | "321" 12 | Given n and k, return the kth permutation sequence. 13 | ''' 14 | 15 | class Solution: 16 | # @return a string 17 | def getPermutation(self, n, k): 18 | d, ans, use = [0, 1], [], ['0'] * n 19 | for i in range(2, 10) : d.append( i * d[-1]) 20 | for i in range(n): 21 | ans.append(0) 22 | for j in range(n): 23 | if use[j] == 1: 24 | continue; 25 | ans[i] = chr(ord('0') + j + 1) 26 | if k <= d[n-i-1]: 27 | use[j] = 1 28 | break 29 | k -= d[n-i-1] 30 | return ''.join(ans) 31 | -------------------------------------------------------------------------------- /20120625 Subsets II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of integers that might contain duplicates, S, return all possible subsets. 3 | 4 | Note: 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 | class Solution: 20 | # @param num, a list of integer 21 | # @return a list of lists of integer 22 | def subsetsWithDup(self, S): 23 | S.sort() 24 | bset = [] 25 | for x in range(2**len(S)): 26 | for i in range(1, len(S)): 27 | if (S[i] == S[i-1] and (x>>(i-1)&0x03 == 0x01)): break 28 | else: 29 | bset.append(x) 30 | return [[S[x] for x in range(len(S)) if i>>x&1] for i in bset] 31 | 32 | S = [] 33 | s = Solution() 34 | print s.subsetsWithDup(S) 35 | -------------------------------------------------------------------------------- /20120118 3Sum Closest.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | For example, given array S = {-1 2 1 -4}, and target = 1. 4 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 5 | ''' 6 | 7 | class Solution: 8 | # @return an integer 9 | def threeSumClosest(self, num, target): 10 | num.sort() 11 | ans = None 12 | for i in range(len(num)): 13 | l, r = i + 1, len(num) - 1 14 | while (l < r): 15 | sum = num[l] + num[r] + num[i] 16 | if ans is None or abs(sum- target) < abs(ans - target): 17 | ans = sum 18 | if sum <= target: 19 | l = l + 1 20 | else: 21 | r = r - 1 22 | return ans 23 | -------------------------------------------------------------------------------- /20120625 Decode Ways.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | 4 | 'A' -> 1 5 | 'B' -> 2 6 | ... 7 | 'Z' -> 26 8 | Given an encoded message containing digits, determine the total number of ways to decode it. 9 | 10 | For example, 11 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 12 | 13 | The number of ways decoding "12" is 2. 14 | ''' 15 | class Solution: 16 | # @param s, a string 17 | # @return an integer 18 | def numDecodings(self, s): 19 | if len(s) == 0: 20 | return 0 21 | dp = [1] + [0] * len(s) 22 | ok = lambda x: x[0] != '0' and int(x) >= 1 and int(x) <= 26; 23 | for i in range(1, len(s) + 1): 24 | dp[i] = dp[i-1] if ok(s[i-1:i]) else 0 25 | if i >= 2: 26 | dp[i]+= dp[i-2] if ok(s[i-2:i]) else 0 27 | return dp[len(s)] 28 | 29 | s = Solution() 30 | print s.numDecodings("23") 31 | -------------------------------------------------------------------------------- /20120229 Longest Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 3 | 4 | For "(()", the longest valid parentheses substring is "()", which has length = 2. 5 | 6 | Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. 7 | ''' 8 | 9 | class Solution: 10 | # @param s, a string 11 | # @return an integer 12 | def longestValidParentheses(self, s): 13 | stk, p ,ans = [], [0] * len(s), 0 14 | for i in range(len(s)): 15 | if s[i] == '(': 16 | stk.append(i) 17 | elif s[i] == ')': 18 | if len(stk) > 0: 19 | p[i] = i - stk[-1] + 1 20 | if i >= p[i] and p[i - p[i]]: 21 | p[i] += p[i-p[i]] 22 | ans = max(ans, p[i]) 23 | stk.pop() 24 | return ans 25 | -------------------------------------------------------------------------------- /20121008 Balanced Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, determine if it is height-balanced. 3 | 4 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | */ 6 | /** 7 | * Definition for binary tree 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | bool isBalanced(TreeNode *root) { 18 | bool ans = true; 19 | dfs(root, ans); 20 | return ans; 21 | 22 | } 23 | int dfs(TreeNode *root, bool &ans) { 24 | if (!root) return 0; 25 | int ltval = dfs(root->left, ans); 26 | int rtval = dfs(root->right, ans); 27 | if (!(ltval - rtval <= 1 && ltval - rtval >= -1)) 28 | ans = false; 29 | return max(ltval, rtval) + 1; 30 | } 31 | }; -------------------------------------------------------------------------------- /20111111 Longest Palindromic Substring.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring 3 | ''' 4 | 5 | class Solution: 6 | # @return a string 7 | def longestPalindrome(self, s): 8 | arr = ['$', '#'] 9 | for i in range(len(s)): 10 | arr.append(s[i]) 11 | arr.append('#') 12 | p = [0] * len(arr) 13 | mx, pos, ansp = 0, 0, 0 14 | for i in range(1, len(arr)): 15 | p[i] = min(mx - i, p[2 * pos - i]) if mx > i else 1 16 | while p[i] + i < len(arr) and arr[i + p[i]] == arr[i - p[i]]: 17 | p[i] += 1 18 | if p[i] + i > mx: 19 | mx, pos = p[i] + i, i 20 | if p[i] > p[ansp]: 21 | ansp = i 22 | st = (ansp - p[ansp] + 1) // 2 23 | return s[st:st + p[ansp] - 1] 24 | 25 | 26 | -------------------------------------------------------------------------------- /20121106 Best Time to Buy and Sell Stock III.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 5 | 6 | Note: 7 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).*/ 8 | class Solution { 9 | public: 10 | int maxProfit(vector &prices) { 11 | int size = prices.size(), ans = 0; 12 | if (size <= 1) return 0; 13 | vector p(size, 0); 14 | int minv = prices[0], maxv; 15 | for (int i = 1; i < size; i++) 16 | p[i] = prices[i] - minv, 17 | minv = min(prices[i], minv); 18 | ans = max(ans, p[size-1]); 19 | minv = prices[size-1], maxv = 0; 20 | for (int i = size-2; i >= 0; i--) 21 | maxv = max(maxv, minv - prices[i]), 22 | ans = max(ans, p[i] + maxv), 23 | minv = max(prices[i], minv); 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /20130112 Valid Palindrome.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 3 | 4 | For example, 5 | "A man, a plan, a canal: Panama" is a palindrome. 6 | "race a car" is not a palindrome. 7 | 8 | Note: 9 | Have you consider that the string might be empty? This is a good question to ask during an interview. 10 | 11 | For the purpose of this problem, we define empty string as valid palindrome. 12 | */ 13 | class Solution { 14 | public: 15 | bool isPalindrome(string s) { 16 | // IMPORTANT: Please reset any member data you declared, as 17 | // the same Solution instance will be reused for each test case. 18 | int len = s.length(), l = 0, r = len - 1; 19 | bool isPal = true; 20 | while (l < r) { 21 | if (!isalnum(s[l])) l++; 22 | else if (!isalnum(s[r])) r--; 23 | else if (tolower(s[l]) == tolower(s[r])) l++, r--; 24 | else return false; 25 | } 26 | return true; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /20120422 Remove Duplicates from Sorted List.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | 6 | ''' 7 | Given a sorted linked list, delete all duplicates such that each element appear only once. 8 | 9 | For example, 10 | Given 1->1->2, return 1->2. 11 | Given 1->1->2->3->3, return 1->2->3. 12 | ''' 13 | 14 | # Definition for singly-linked list. 15 | # class ListNode: 16 | # def __init__(self, x): 17 | # self.val = x 18 | # self.next = None 19 | 20 | class Solution: 21 | # @param head, a ListNode 22 | # @return a ListNode 23 | def deleteDuplicates(self, head): 24 | if not head: 25 | return head 26 | nHead = ListNode(0) 27 | nHead.next, head = head, nHead 28 | while head: 29 | if (head.next and head.next.next and head.next.next.val == head.next.val): 30 | head.next = head.next.next 31 | else: 32 | head = head.next 33 | return nHead.next -------------------------------------------------------------------------------- /20120830 Interleaving String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 3 | 4 | For example, 5 | Given: 6 | s1 = "aabcc", 7 | s2 = "dbbca", 8 | 9 | When s3 = "aadbbcbcac", return true. 10 | When s3 = "aadbbbaccc", return false. 11 | ''' 12 | 13 | class Solution: 14 | # @return a boolean 15 | def isInterleave(self, s1, s2, s3): 16 | if len(s3) != len(s1) + len(s2): 17 | return False 18 | dp = [[False] * (len(s2) + 1) for i in range(len(s1) + 1)] 19 | for i in range(len(s1) + 1): 20 | for j in range(len(s2) + 1): 21 | if i == 0 and j == 0: 22 | dp[i][j] = True 23 | elif i > 0 and dp[i-1][j] and s3[i+j-1] == s1[i-1]: 24 | dp[i][j] = True 25 | elif j > 0 and dp[i][j-1] and s3[i+j-1] == s2[j-1]: 26 | dp[i][j] = True 27 | else: 28 | dp[i][j] = False 29 | return dp[len(s1)][len(s2)] 30 | -------------------------------------------------------------------------------- /20121107 Binary Tree Maximum Path Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, find the maximum path sum. 3 | 4 | The path may start and end at any node in the tree. 5 | 6 | For example: 7 | Given the below binary tree, 8 | 9 | 1 10 | / \ 11 | 2 3 12 | Return 6. 13 | */ 14 | 15 | /** 16 | * Definition for binary tree 17 | * struct TreeNode { 18 | * int val; 19 | * TreeNode *left; 20 | * TreeNode *right; 21 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 22 | * }; 23 | */ 24 | class Solution { 25 | public: 26 | int maxPathSum(TreeNode *root) { 27 | int ans = root->val; 28 | dfsTree(root, ans); 29 | return ans; 30 | } 31 | int dfsTree(TreeNode *fa, int &ans) { 32 | if (fa == NULL) return 0; 33 | int tmp = fa->val, lmax, rmax; 34 | if ((lmax = dfsTree(fa->left, ans)) > 0) tmp += lmax; 35 | if ((rmax = dfsTree(fa->right, ans)) > 0) tmp += rmax; 36 | ans = max(ans, tmp); 37 | return max(fa->val, max(fa->val+lmax, fa->val+rmax)); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /20121018 Distinct Subsequences.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S and a string T, count the number of distinct subsequences of T in S. 3 | 4 | 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). 5 | 6 | Here is an example: 7 | S = "rabbbit", T = "rabbit" 8 | 9 | Return 3. 10 | */ 11 | class Solution { 12 | public: 13 | int numDistinct(string S, string T) { 14 | int lent = T.length(), lens = S.length(); 15 | vector > dp(lent+1, vector(lens+1, 0)); 16 | for (int i = 0; i <= lens; i++) dp[0][i] = 1; 17 | for (int i = 1; i <= lent; i++) { 18 | for (int j = 1; j <= lens; j++) { 19 | dp[i][j] = dp[i][j-1]; 20 | if (S[j-1] == T[i-1]) 21 | dp[i][j] += dp[i-1][j-1]; 22 | } 23 | } 24 | return dp[lent][lens]; 25 | } 26 | }; -------------------------------------------------------------------------------- /20120316 Permutations.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of numbers, return all possible permutations. 3 | 4 | For example, 5 | [1,2,3] have the following permutations: 6 | [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. 7 | ''' 8 | class Solution: 9 | # @param num, a list of integer 10 | # @return a list of lists of integers 11 | def permute(self, num): 12 | num.sort() 13 | ans = [num[:]] 14 | while self.next_permutation(num): 15 | ans.append(num[:]) 16 | return ans 17 | 18 | def next_permutation(self, num): 19 | for i in range(len(num)-2, -1, -1): 20 | if num[i] < num[i+1]: 21 | break 22 | else: 23 | return False 24 | 25 | for j in range(len(num)-1, i, -1): 26 | if num[j] > num[i]: 27 | num[i], num[j] = num[j], num[i] 28 | break 29 | for j in range(0, (len(num) - i)//2): 30 | num[i+j+1], num[len(num)-j-1] = num[len(num)-j-1], num[i+j+1] 31 | return True 32 | -------------------------------------------------------------------------------- /20120422 Largest Rectangle in Histogram.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. 3 | 4 | 5 | Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. 6 | 7 | 8 | The largest rectangle is shown in the shaded area, which has area = 10 unit. 9 | 10 | For example, 11 | Given height = [2,1,5,6,2,3], 12 | return 10. 13 | ''' 14 | 15 | class Solution: 16 | # @param height, a list of integer 17 | # @return an integer 18 | def largestRectangleArea(self, height): 19 | ans, lenh, stk = 0, len(height), [] 20 | for i in range(lenh + 1): 21 | while len(stk) and (i == lenh or height[stk[-1]] >= height[i]): 22 | top = stk.pop() 23 | if len(stk) == 0: 24 | ans = max(ans, height[top] * i) 25 | else: 26 | ans = max(ans, height[top] * (i - stk[-1] - 1)) 27 | stk.append(i) 28 | return ans 29 | -------------------------------------------------------------------------------- /20131107 Binary Tree Postorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector vec; 13 | vector postorderTraversal(TreeNode *root) { 14 | stack st; 15 | vec.clear(); 16 | TreeNode *T = root, *last = NULL; 17 | while (T || !st.empty()) { 18 | if (T) { 19 | st.push(T); 20 | T = T->left; 21 | } else { 22 | T = st.top(); 23 | if ((!T->left && !T->right) || (T->left == last && !T->right) 24 | || (T->right == last)) { 25 | vec.push_back(T->val); 26 | last = T, T = NULL; 27 | st.pop(); 28 | } else { 29 | T = T->right; 30 | } 31 | } 32 | } 33 | return vec; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /20120218 Implement strStr().py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement strStr(). 3 | Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 4 | ''' 5 | class Solution: 6 | # @param haystack, a string 7 | # @param needle, a string 8 | # @return a string or None 9 | def strStr(self, haystack, needle): 10 | lenh, lenn = len(haystack), len(needle) 11 | if lenn == 0: 12 | return haystack 13 | next, p = [-1] * (lenn), -1 14 | for i in range(1, lenn): 15 | while p >= 0 and needle[i] != needle[p + 1]: 16 | p = next[p] 17 | if needle[i] == needle[p + 1]: 18 | p = p + 1 19 | next[i] = p 20 | p = -1 21 | for i in range(lenh): 22 | while p >= 0 and haystack[i] != needle[p + 1]: 23 | p = next[p] 24 | if haystack[i] == needle[p + 1]: 25 | p = p + 1 26 | if p + 1 == lenn: 27 | return haystack[i - p:] 28 | return None 29 | -------------------------------------------------------------------------------- /20120327 Rotate List.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | 6 | ''' 7 | Given a list, rotate the list to the right by k places, where k is non-negative. 8 | 9 | For example: 10 | Given 1->2->3->4->5->NULL and k = 2, 11 | return 4->5->1->2->3->NULL. 12 | ''' 13 | # Definition for singly-linked list. 14 | # class ListNode: 15 | # def __init__(self, x): 16 | # self.val = x 17 | # self.next = None 18 | 19 | class Solution: 20 | # @param head, a ListNode 21 | # @param k, an integer 22 | # @return a ListNode 23 | def rotateRight(self, head, k): 24 | if not head: 25 | return head 26 | p, len = head, 1 27 | while p.next: 28 | p, len = p.next, len + 1 29 | k = len - k % len 30 | if k == len: 31 | return head 32 | pp, len = head, 1 33 | while len < k: 34 | pp, len = pp.next, len + 1 35 | p.next, head, pp.next = head, pp.next, None 36 | return head 37 | 38 | -------------------------------------------------------------------------------- /20120316 Permutations II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 3 | 4 | For example, 5 | [1,1,2] have the following unique permutations: 6 | [1,1,2], [1,2,1], and [2,1,1]. 7 | ''' 8 | 9 | class Solution: 10 | # @param num, a list of integer 11 | # @return a list of lists of integers 12 | def permuteUnique(self, num): 13 | num.sort() 14 | ans = [num[:]] 15 | while self.next_permutation(num): 16 | ans.append(num[:]) 17 | return ans 18 | 19 | def next_permutation(self, num): 20 | for i in range(len(num)-2, -1, -1): 21 | if num[i] < num[i+1]: 22 | break 23 | else: 24 | return False 25 | 26 | for j in range(len(num)-1, i, -1): 27 | if num[j] > num[i]: 28 | num[i], num[j] = num[j], num[i] 29 | break 30 | for j in range(0, (len(num) - i)//2): 31 | num[i+j+1], num[len(num)-j-1] = num[len(num)-j-1], num[i+j+1] 32 | return True -------------------------------------------------------------------------------- /20120330 Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | ''' 6 | 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. 7 | ''' 8 | 9 | # Definition for singly-linked list. 10 | # class ListNode: 11 | # def __init__(self, x): 12 | # self.val = x 13 | # self.next = None 14 | 15 | class Solution: 16 | # @param two ListNodes 17 | # @return a ListNode 18 | def mergeTwoLists(self, l1, l2): 19 | nHead = ListNode(0) 20 | lt, rt, backHead = l1, l2, nHead 21 | while lt or rt: 22 | if lt is None: 23 | nHead.next, rt = rt, rt.next 24 | elif rt is None: 25 | nHead.next, lt = lt, lt.next 26 | elif lt.val < rt.val: 27 | nHead.next, lt = lt, lt.next 28 | else: 29 | nHead.next, rt = rt, rt.next 30 | nHead = nHead.next 31 | return backHead.next 32 | -------------------------------------------------------------------------------- /20120404 Edit Distance.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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.) 3 | 4 | You have the following 3 operations permitted on a word: 5 | 6 | a) Insert a character 7 | b) Delete a character 8 | c) Replace a character 9 | ''' 10 | 11 | class Solution: 12 | # @return an integer 13 | def minDistance(self, word1, word2): 14 | dp = [[0] * (len(word2) + 1) for i in range(len(word1) + 1)] 15 | for i in range(1, len(word1) + 1): 16 | dp[i][0] = i 17 | for i in range(1, len(word2) + 1): 18 | dp[0][i] = i 19 | for i in range(1, len(word1) + 1): 20 | for j in range(1, len(word2) + 1): 21 | dp[i][j] = dp[i - 1][j - 1] + 1 22 | if word1[i - 1] == word2[j - 1]: 23 | dp[i][j] = dp[i - 1][j - 1] 24 | dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1) 25 | dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1) 26 | return dp[len(word1)][len(word2)] 27 | -------------------------------------------------------------------------------- /20130928 Gas Station.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 3 | 4 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. 5 | 6 | Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. 7 | 8 | Note: 9 | The solution is guaranteed to be unique. 10 | */ 11 | 12 | class Solution { 13 | public: 14 | int canCompleteCircuit(vector &gas, vector &cost) { 15 | // IMPORTANT: Please reset any member data you declared, as 16 | // the same Solution instance will be reused for each test case. 17 | int remain = 0, totgas = 0, startp = 0; 18 | for (int i = 0; i < gas.size(); i++) { 19 | remain += gas[i] - cost[i]; 20 | totgas += gas[i] - cost[i]; 21 | if (remain < 0) remain = 0, startp = i + 1; 22 | } 23 | startp %= gas.size(); 24 | return totgas >= 0 ? startp : -1; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /20120324 Spiral Matrix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 3 | 4 | For example, 5 | Given the following matrix: 6 | 7 | [ 8 | [ 1, 2, 3 ], 9 | [ 4, 5, 6 ], 10 | [ 7, 8, 9 ] 11 | ] 12 | You should return [1,2,3,6,9,8,7,4,5]. 13 | ''' 14 | 15 | class Solution: 16 | # @param matrix, a list of lists of integers 17 | # @return a list of integers 18 | def spiralOrder(self, matrix): 19 | if len(matrix) == 0: 20 | return [] 21 | a, ans, m, n = matrix, [], len(matrix), len(matrix[0]) 22 | x = [[0] * n for i in range(m)] 23 | sx, sy = 0, 0 24 | dx, dy, dn = [0, 1, 0, -1], [1, 0, -1, 0], 0 25 | for i in range(m * n): 26 | ans.append(a[sx][sy]) 27 | x[sx][sy] = 1 28 | nx, ny = sx + dx[dn], sy + dy[dn] 29 | if nx < 0 or nx < 0 or nx >= m or ny >= n or x[nx][ny]: 30 | dn = (dn + 1) % 4 31 | nx, ny = sx + dx[dn], sy + dy[dn] 32 | sx, sy = nx, ny 33 | return ans 34 | -------------------------------------------------------------------------------- /20130228 Palindrome Partitioning II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return the minimum cuts needed for a palindrome partitioning of s. 5 | 6 | For example, given s = "aab", 7 | Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. 8 | */ 9 | class Solution { 10 | public: 11 | int minCut(string s) { 12 | // IMPORTANT: Please reset any member data you declared, as 13 | // the same Solution instance will be reused for each test case. 14 | vector > isPar(s.length(), vector(s.length(), false)); 15 | vector minC(s.length(), 0); 16 | for (int i = 0; i < s.length(); i++) { 17 | minC[i] = i + 1; 18 | for (int j = 0; j <= i; j++) { 19 | if ((j + 2 > i || isPar[j+1][i-1]) && s[j] == s[i]) { 20 | isPar[j][i] = true; 21 | minC[i] = min(minC[i], j ? (minC[j-1] + 1) : 1); 22 | } 23 | } 24 | } 25 | return minC[s.length() - 1] - 1; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /20120406 Search a 2D Matrix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 3 | 4 | Integers in each row are sorted from left to right. 5 | The first integer of each row is greater than the last integer of the previous row. 6 | For example, 7 | 8 | Consider the following matrix: 9 | 10 | [ 11 | [1, 3, 5, 7], 12 | [10, 11, 16, 20], 13 | [23, 30, 34, 50] 14 | ] 15 | Given target = 3, return true. 16 | ''' 17 | class Solution: 18 | # @param matrix, a list of lists of integers 19 | # @param target, an integer 20 | # @return a boolean 21 | def searchMatrix(self, matrix, target): 22 | l, h = 0, len(matrix) * len(matrix[0]) - 1 23 | while (l <= h): 24 | m = l + ((h-l) >> 2) 25 | v = matrix[m/len(matrix[0])][m%len(matrix[0])] 26 | if v < target: 27 | l = m + 1 28 | elif v > target: 29 | h = m - 1 30 | else: 31 | return True 32 | return False 33 | 34 | 35 | -------------------------------------------------------------------------------- /20120326 Merge Intervals.py: -------------------------------------------------------------------------------- 1 | class Interval: 2 | def __init__(self, s=0, e=0): 3 | self.start = s 4 | self.end = e 5 | ''' 6 | Given a collection of intervals, merge all overlapping intervals. 7 | 8 | For example, 9 | Given [1,3],[2,6],[8,10],[15,18], 10 | return [1,6],[8,10],[15,18]. 11 | ''' 12 | 13 | # Definition for an interval. 14 | # class Interval: 15 | # def __init__(self, s=0, e=0): 16 | # self.start = s 17 | # self.end = e 18 | 19 | class Solution: 20 | # @param intervals, a list of Interval 21 | # @return a list of Interval 22 | def merge(self, intervals): 23 | intervals.sort(cmp = lambda x, y: cmp(x.start, y.start) or (x.start == y.start and cmp(x.end,y.end))) 24 | ans, p, maxr = [], 0, 0 25 | for i in range(len(intervals) + 1): 26 | if i > 0 and (i == len(intervals) or intervals[i].start > maxr): 27 | ans.append(Interval(intervals[p].start, maxr)) 28 | p = i 29 | if i < len(intervals): 30 | maxr = max(maxr, intervals[i].end) 31 | return ans 32 | 33 | -------------------------------------------------------------------------------- /20120827 Binary Tree Inorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the inorder traversal of its nodes' values. 3 | 4 | For example: 5 | Given binary tree {1,#,2,3}, 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 | * Definition for binary tree 17 | * struct TreeNode { 18 | * int val; 19 | * TreeNode *left; 20 | * TreeNode *right; 21 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 22 | * }; 23 | */ 24 | class Solution { 25 | public: 26 | vector vec; 27 | vector inorderTraversal(TreeNode *root) { 28 | stack st; 29 | vec.clear(); 30 | TreeNode *T = root; 31 | while (T || !st.empty()) { 32 | if (T) { 33 | st.push(T); 34 | T = T->left; 35 | } else { 36 | T = st.top(); st.pop(); 37 | vec.push_back(T->val); 38 | T = T->right; 39 | } 40 | } 41 | return vec; 42 | } 43 | }; -------------------------------------------------------------------------------- /20110327 Median of Two Sorted Arrays.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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)) 3 | ''' 4 | 5 | class Solution: 6 | # @return a float 7 | def findMedianSortedArrays(self, A, B): 8 | totlen = len(A) + len(B) 9 | if (1 & totlen): 10 | return self.findK(A, B, (totlen + 1) / 2) 11 | else: 12 | return (self.findK(A, B, totlen / 2) + self.findK(A, B, totlen / 2 + 1)) / 2.0 13 | 14 | def findK(self, A, B, K): 15 | la, lb, pa, pb = len(A), len(B), min(K/2, len(A)), K - min(K/2, len(A)) 16 | if (la > lb): 17 | return self.findK(B, A, K) 18 | if (la == 0): 19 | return B[K-1] 20 | if (K == 1): 21 | return min(A[0], B[0]) 22 | if A[pa - 1] < B[pb - 1]: 23 | return self.findK(A[pa:], B, K - pa) 24 | elif A[pa - 1] > B[pb - 1]: 25 | return self.findK(A, B[pb:], K- pb) 26 | else: 27 | return A[pa - 1] 28 | 29 | -------------------------------------------------------------------------------- /20120423 Maximal Rectangle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. 3 | ''' 4 | class Solution: 5 | # @param matrix, a list of lists of 1 length string 6 | # @return an integer 7 | def maximalRectangle(self, matrix): 8 | if len(matrix) == 0: 9 | return 0 10 | ans = 0; 11 | for i in range(len(matrix)): 12 | stk = [] 13 | for j in range(len(matrix[0]) + 1): 14 | if j < len(matrix[0]): matrix[i][j] = int(matrix[i][j]) 15 | if i > 0 and j < len(matrix[0]) and matrix[i][j]: 16 | matrix[i][j] += matrix[i-1][j] 17 | while len(stk) and (j == len(matrix[0]) or matrix[i][stk[-1]] >= matrix[i][j]): 18 | top = stk.pop() 19 | if len(stk) == 0: 20 | ans = max(ans, matrix[i][top]*j) 21 | else: 22 | ans = max(ans, matrix[i][top]*(j-stk[-1]-1)) 23 | stk.append(j) 24 | return ans 25 | -------------------------------------------------------------------------------- /20120807 Restore IP Addresses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 3 | 4 | For example: 5 | Given "25525511135", 6 | 7 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 8 | */ 9 | class Solution { 10 | public: 11 | vector ans; 12 | vector restoreIpAddresses(string s) { 13 | ans.clear(); 14 | dfs(ans, s, "", 0, 0); 15 | return ans; 16 | } 17 | void dfs(vector &ans, string s, string str, int pos, int dep) { 18 | if (dep >= 4) { 19 | if (dep == 4 && pos == s.length()) ans.push_back(str); 20 | } else { 21 | for (int i = pos; i < s.length(); i++) { 22 | string sub = s.substr(pos, i-pos+1); 23 | if (sub.length() <= 3 && stoi(sub) >= 0 && stoi(sub) <= 255 && 24 | to_string(stoi(sub)) == sub) { 25 | string common = (dep == 3 ? "": "."); 26 | dfs(ans, s, str+sub+common, i+1, dep+1); 27 | } 28 | } 29 | } 30 | } 31 | }; -------------------------------------------------------------------------------- /20130213 Longest Consecutive Sequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 3 | 4 | For example, 5 | Given [100, 4, 200, 1, 3, 2], 6 | The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. 7 | 8 | Your algorithm should run in O(n) complexity. 9 | */ 10 | 11 | class Solution { 12 | public: 13 | int longestConsecutive(vector &num) { 14 | // IMPORTANT: Please reset any member data you declared, as 15 | // the same Solution instance will be reused for each test case. 16 | unordered_set uset; 17 | for (int i = 0; i < num.size(); i++) 18 | uset.insert(num[i]); 19 | int ans = 0, tmpAns = 0, now, nowb; 20 | while (!uset.empty()) { 21 | now = *uset.begin(), tmpAns = 1; 22 | uset.erase(now); 23 | for (nowb = now + 1; uset.count(nowb); uset.erase(nowb), tmpAns++, nowb++); 24 | for (nowb = now - 1; uset.count(nowb); uset.erase(nowb), tmpAns++, nowb--); 25 | if (tmpAns > ans) ans = tmpAns; 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /20131004 Word Break.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. 3 | 4 | For example, given 5 | s = "leetcode", 6 | dict = ["leet", "code"]. 7 | 8 | Return true because "leetcode" can be segmented as "leet code". 9 | */ 10 | class Solution { 11 | public: 12 | bool wordBreak(string s, unordered_set &dict) { 13 | // IMPORTANT: Please reset any member data you declared, as 14 | // the same Solution instance will be reused for each test case. 15 | vector > dp(s.length(), vector(s.length(), -1)); 16 | return dpit(dp, s, dict, 0, s.length() - 1); 17 | } 18 | bool dpit(vector > &dp, string &s, unordered_set &dict, int l, int r) { 19 | if (dp[l][r] != -1) return dp[l][r]; 20 | if (dict.find(s.substr(l, r - l + 1)) != dict.end()) return dp[l][r] = 1; 21 | for (int i = l; i < r; i++) { 22 | if (dpit(dp, s, dict, l, i) && dpit(dp, s, dict, i+1, r)) 23 | return dp[l][r] = 1; 24 | } 25 | return dp[l][r] = 0; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /20131112 Insertion Sort List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *insertionSortList(ListNode *head) { 12 | // IMPORTANT: Please reset any member data you declared, as 13 | // the same Solution instance will be reused for each test case. 14 | if (head == NULL) return head; 15 | ListNode *newHead = new ListNode(0); 16 | ListNode *nextHead = head->next, *now; 17 | newHead->next = head, head->next = NULL; 18 | while (nextHead != NULL){ 19 | now = nextHead, nextHead = nextHead->next; 20 | for (ListNode *h = newHead; h != NULL; h = h->next) { 21 | if (h->next == NULL || now->val < h->next->val) { 22 | ListNode *tmp = h->next; 23 | h->next = now, now->next = tmp; 24 | break; 25 | } 26 | } 27 | } 28 | head = newHead->next; 29 | delete newHead; 30 | return head; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /20120216 Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 3 | 4 | Do not allocate extra space for another array, you must do this in place with constant memory. 5 | 6 | For example, 7 | Given input array A = [1,1,2], 8 | 9 | Your function should return length = 2, and A is now [1,2]. 10 | ''' 11 | # class Solution: 12 | # # @param a list of integers 13 | # # @return an integer 14 | # def removeDuplicates(self, A): 15 | # if len(A) == 0: 16 | # return 0 17 | # sz = 1 18 | # for i in range(1, len(A)): 19 | # if A[i] != A[i-1]: 20 | # A[sz] = A[i] 21 | # sz += 1 22 | # return sz 23 | 24 | class Solution: 25 | # @param A a list of integers 26 | # @return an integer 27 | def removeDuplicates(self, A): 28 | sz = 0 29 | for i in range(len(A)): 30 | if sz < 2 or A[sz - 2] != A[i]: 31 | A[sz] = A[i] 32 | sz = sz + 1 33 | return sz 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /20131102 Reorder List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void reorderList(ListNode *head) { 12 | // IMPORTANT: Please reset any member data you declared, as 13 | // the same Solution instance will be reused for each test case. 14 | int len = 0, i; 15 | ListNode *p, *last, *pnext, *tmp; 16 | for (p = head; p; p = p->next, len++); 17 | if (len <= 2) return; 18 | for (p = head, i = 0; i < len/2; p = p->next, i++); 19 | tmp = p, p = p->next, tmp->next = NULL; 20 | for (pnext = p->next, p->next = NULL; pnext;) { 21 | tmp = pnext; 22 | pnext = pnext->next; 23 | tmp->next = p; 24 | p = tmp; 25 | } 26 | last = p; 27 | for (p = head; p; p = tmp){ 28 | tmp = p->next; 29 | if (last) { 30 | p->next = last; 31 | last = last->next; 32 | p->next->next = tmp; 33 | } 34 | } 35 | } 36 | }; 37 | 38 | -------------------------------------------------------------------------------- /20120319 N-Queens.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other. 3 | Given an integer n, return all distinct solutions to the n-queens puzzle. 4 | Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. 5 | ''' 6 | 7 | class Solution: 8 | # @return a list of lists of string 9 | def solveNQueens(self, n): 10 | self.ans, self.dt = [], {} 11 | self.full = ((1 << n) - 1) 12 | for i in range(n): self.dt[1<>1, (rt|now)<<1, nt|now, tmp) 26 | tmp[p][self.dt[now]] = '.' 27 | can -= now 28 | -------------------------------------------------------------------------------- /20111205 ZigZag Conversion.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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) 3 | 4 | P A H N 5 | A P L S I I G 6 | Y I R 7 | And then read line by line: "PAHNAPLSIIGYIR" 8 | Write the code that will take a string and make this conversion given a number of rows: 9 | 10 | string convert(string text, int nRows); 11 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 12 | ''' 13 | 14 | class Solution: 15 | # @return a string 16 | def convert(self, s, nRows): 17 | if nRows == 1 or len(s) == 0: 18 | return s 19 | res, lens = [], len(s) 20 | add, now = [nRows * 2 - 2, 0], 0 21 | for i in range(nRows): 22 | if i < lens: 23 | res.append(i) 24 | while res[-1] + add[now] < lens: 25 | if add[now] > 0: 26 | res.append(res[-1] + add[now]) 27 | now ^= 1 28 | add, now = [add[0] - 2, add[1] + 2], 0 29 | return ''.join([s[i] for i in res]) 30 | 31 | s = Solution() 32 | print s.convert("A", 2) -------------------------------------------------------------------------------- /20120930 Construct Binary Tree from Preorder and Inorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given preorder and inorder traversal of a tree, construct the binary tree. 3 | 4 | Note: 5 | You may assume that duplicates do not exist in the tree. 6 | */ 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | TreeNode *buildTree(vector &preorder, vector &inorder) { 19 | return build(0, preorder.size()-1, 0, inorder.size()-1, preorder, inorder); 20 | } 21 | TreeNode *build(int pl, int pr, int il, int ir, vector &pvec, vector &ivec) { 22 | if (pl > pr) return NULL; 23 | TreeNode *node = new TreeNode(pvec[pl]); 24 | int ip; 25 | for (ip = il; ip <= ir; ip++) { 26 | if (ivec[ip] == pvec[pl]) break; 27 | } 28 | if (il<=ip-1) node->left = build(pl+1, pl+ip-il, il, ip-1, pvec, ivec); 29 | if (ip+1<=ir) node->right = build(pl+ip-il+1, pr, ip+1, ir, pvec, ivec); 30 | return node; 31 | } 32 | }; -------------------------------------------------------------------------------- /20120930 Construct Binary Tree from Inorder and Postorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given inorder and postorder traversal of a tree, construct the binary tree. 3 | 4 | Note: 5 | You may assume that duplicates do not exist in the tree. 6 | */ 7 | /** 8 | * Definition for binary tree 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | TreeNode *buildTree(vector &inorder, vector &postorder) { 19 | return build(0, inorder.size()-1, 0, postorder.size()-1, inorder, postorder); 20 | } 21 | TreeNode *build(int il, int ir, int pl, int pr, vector &ivec, vector &pvec) { 22 | if (pl > pr) return NULL; 23 | TreeNode *node = new TreeNode(pvec[pr]); 24 | int ip; 25 | for (ip = il; ip <= ir; ip++) { 26 | if (ivec[ip] == pvec[pr]) break; 27 | } 28 | if (il<=ip-1) node->left = build(il, ip-1, pl, pl+ip-il-1, ivec, pvec); 29 | if (ip+1<=ir) node->right = build(ip+1, ir, pl+ip-il, pr-1, ivec, pvec); 30 | return node; 31 | } 32 | }; -------------------------------------------------------------------------------- /20120117 3Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | Note: 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 | 9 | class Solution: 10 | # @return a list of lists of length 3, [[val1,val2,val3]] 11 | def threeSum(self, num): 12 | num.sort() 13 | dct, ans = {}, [] 14 | for i in range(0, len(num)): 15 | if (i > 0 and num[i] == num[i-1]): 16 | continue 17 | l, r = i + 1, len(num) - 1 18 | while l < r: 19 | sum = num[l] + num[r] + num[i] 20 | if sum == 0: 21 | ans.append([num[i], num[l], num[r]]) 22 | while l < r and num[l] == num[l + 1]: l = l + 1 23 | while l < r and num[r] == num[r - 1]: r = r - 1 24 | l, r = l + 1, r - 1 25 | elif sum < 0: 26 | l = l + 1 27 | else: 28 | r = r - 1 29 | return ans 30 | 31 | -------------------------------------------------------------------------------- /20120225 Next Permutation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 3 | 4 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 5 | 6 | The replacement must be in-place, do not allocate extra memory. 7 | 8 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 9 | 1,2,3 -> 1,3,2 10 | 3,2,1 -> 1,2,3 11 | 1,1,5 -> 1,5,1 12 | ''' 13 | 14 | class Solution: 15 | # @param num, a list of integer 16 | # @return a list of integer 17 | def nextPermutation(self, num): 18 | for i in range(len(num)-2, -1, -1): 19 | if num[i] < num[i+1]: 20 | break 21 | else: 22 | num.reverse() 23 | return num 24 | 25 | for j in range(len(num)-1, i, -1): 26 | if num[j] > num[i]: 27 | num[i], num[j] = num[j], num[i] 28 | break 29 | for j in range(0, (len(num) - i)//2): 30 | num[i+j+1], num[len(num)-j-1] = num[len(num)-j-1], num[i+j+1] 31 | return num 32 | -------------------------------------------------------------------------------- /20120328 Unique Paths II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 3 | 4 | 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). 5 | 6 | How many possible unique paths are there? 7 | ''' 8 | 9 | class Solution: 10 | # @param obstacleGrid, a list of lists of integers 11 | # @return an integer 12 | def uniquePathsWithObstacles(self, obstacleGrid): 13 | ans = [[0] * len(obstacleGrid[0]) for i in range(len(obstacleGrid))] 14 | for i in range(len(obstacleGrid)): 15 | if obstacleGrid[i][0] == 1: break 16 | else: ans[i][0] = 1 17 | for i in range(len(obstacleGrid[0])): 18 | if obstacleGrid[0][i] == 1: break 19 | else: ans[0][i] = 1 20 | for i in range(1, len(obstacleGrid)): 21 | for j in range(1, len(obstacleGrid[0])): 22 | if obstacleGrid[i][j] == 1: 23 | ans[i][j] = 0 24 | else: 25 | ans[i][j] = ans[i][j-1] + ans[i-1][j] 26 | return ans[len(ans)-1][len(ans[0])-1] 27 | -------------------------------------------------------------------------------- /20121013 Path Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | 4 | For example: 5 | Given the below binary tree and sum = 22, 6 | 5 7 | / \ 8 | 4 8 9 | / / \ 10 | 11 13 4 11 | / \ \ 12 | 7 2 1 13 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 14 | */ 15 | /** 16 | * Definition for binary tree 17 | * struct TreeNode { 18 | * int val; 19 | * TreeNode *left; 20 | * TreeNode *right; 21 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 22 | * }; 23 | */ 24 | class Solution { 25 | public: 26 | bool hasPathSum(TreeNode *root, int sum) { 27 | return root && dfs(root, 0, sum) ; 28 | } 29 | bool dfs(TreeNode *node, int now, int sum) { 30 | if (node ->left == NULL && node->right == NULL) 31 | return now + node->val == sum ; 32 | if (node->left && dfs(node->left, now + node->val, sum)) return true; 33 | if (node->right && dfs(node->right, now + node->val, sum)) return true; 34 | return false; 35 | } 36 | }; -------------------------------------------------------------------------------- /20131122 Max Points on a Line.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a point. 3 | * struct Point { 4 | * int x; 5 | * int y; 6 | * Point() : x(0), y(0) {} 7 | * Point(int a, int b) : x(a), y(b) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int maxPoints(vector &points) { 13 | // IMPORTANT: Please reset any member data you declared, as 14 | // the same Solution instance will be reused for each test case. 15 | int size = points.size(); 16 | int ans = 0, horz, same; 17 | map mp; 18 | map::iterator it; 19 | for (int i = 0; i < size; i++) { 20 | mp.clear(); horz = same = 0; 21 | for (int j = 0; j < points.size(); j++) { 22 | if (points[j].x == points[i].x && points[j].y == points[i].y) same++; 23 | else if (points[j].x == points[i].x) horz ++; 24 | else mp[(points[j].y-points[i].y)*1.0/(points[j].x-points[i].x)]++; 25 | } 26 | if (horz + same > ans) ans = horz + same; 27 | for (it = mp.begin(); it != mp.end(); it++) 28 | if (it->second + same > ans) ans = it->second + same; 29 | } 30 | return ans; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /20121002 Convert Sorted List to Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 3 | */ 4 | /** 5 | * Definition for singly-linked list. 6 | * struct ListNode { 7 | * int val; 8 | * ListNode *next; 9 | * ListNode(int x) : val(x), next(NULL) {} 10 | * }; 11 | */ 12 | /** 13 | * Definition for binary tree 14 | * struct TreeNode { 15 | * int val; 16 | * TreeNode *left; 17 | * TreeNode *right; 18 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 19 | * }; 20 | */ 21 | class Solution { 22 | public: 23 | TreeNode *sortedListToBST(ListNode *head) { 24 | int len = 0; 25 | for (ListNode *p = head; p; p = p->next, len++); 26 | return dfs(head, len); 27 | } 28 | TreeNode *dfs(ListNode *head, int len) { 29 | if (len <= 0) return NULL; 30 | int mid = (len + 1) >> 1; 31 | ListNode *rhead = head; 32 | for (int i = 1; i < mid; rhead=rhead->next, i++); 33 | TreeNode *node = new TreeNode(rhead->val); 34 | node->left = dfs(head, mid - 1); 35 | node->right = dfs(rhead->next, len - mid); 36 | return node; 37 | } 38 | }; -------------------------------------------------------------------------------- /20120928 Binary Tree Level Order Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 | 4 | For example: 5 | Given binary tree {3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its level order traversal as: 12 | [ 13 | [3], 14 | [9,20], 15 | [15,7] 16 | ] 17 | confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 18 | */ 19 | /** 20 | * Definition for binary tree 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | vector > vec; 31 | vector > levelOrder(TreeNode *root) { 32 | vec.clear(); 33 | dfs(root, 0, vec); 34 | return vec; 35 | } 36 | void dfs(TreeNode *root, int dep, vector > &vec) { 37 | if (root == NULL) return; 38 | if (vec.size() <= dep) vec.push_back(vector()); 39 | vec[dep].push_back(root->val); 40 | dfs(root->left, dep+1, vec); 41 | dfs(root->right, dep+1, vec); 42 | } 43 | }; -------------------------------------------------------------------------------- /20121001 Binary Tree Level Order Traversal II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 3 | 4 | For example: 5 | Given binary tree {3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its bottom-up level order traversal as: 12 | [ 13 | [15,7] 14 | [9,20], 15 | [3], 16 | ] 17 | */ 18 | /** 19 | * Definition for binary tree 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | vector > vec; 30 | vector > levelOrderBottom(TreeNode *root) { 31 | vec.clear(); 32 | dfs(root, 0, vec); 33 | reverse(vec.begin(), vec.end()); 34 | return vec; 35 | } 36 | void dfs(TreeNode *root, int dep, vector > &vec) { 37 | if (root == NULL) return; 38 | if (vec.size() <= dep) vec.push_back(vector()); 39 | vec[dep].push_back(root->val); 40 | dfs(root->left, dep+1, vec); 41 | dfs(root->right, dep+1, vec); 42 | } 43 | }; -------------------------------------------------------------------------------- /20120831 Validate Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.left = None 5 | self.right = None 6 | 7 | ''' 8 | Given a binary tree, determine if it is a valid binary search tree (BST). 9 | 10 | Assume a BST is defined as follows: 11 | 12 | The left subtree of a node contains only nodes with keys less than the node's key. 13 | The right subtree of a node contains only nodes with keys greater than the node's key. 14 | Both the left and right subtrees must also be binary search trees. 15 | ''' 16 | # Definition for a binary tree node 17 | # class TreeNode: 18 | # def __init__(self, x): 19 | # self.val = x 20 | # self.left = None 21 | # self.right = None 22 | 23 | class Solution: 24 | # @param root, a tree node 25 | # @return a boolean 26 | val = None 27 | def isValidBST(self, root): 28 | if root is None: 29 | return True 30 | res = self.isValidBST(root.left) 31 | if self.val is None: 32 | self.val = root.val 33 | else: 34 | res = res and (root.val > self.val) 35 | self.val = root.val 36 | res = res and self.isValidBST(root.right) 37 | return res 38 | -------------------------------------------------------------------------------- /20131003 Copy List with Random Pointer.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list with a random pointer. 3 | * struct RandomListNode { 4 | * int label; 5 | * RandomListNode *next, *random; 6 | * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | RandomListNode *copyRandomList(RandomListNode *head) { 12 | // IMPORTANT: Please reset any member data you declared, as 13 | // the same Solution instance will be reused for each test case. 14 | if (!head) return NULL; 15 | RandomListNode *bhead, *anow, *bnow; 16 | for (anow = head; anow; anow = anow->next) { 17 | bnow = new RandomListNode(anow->label); 18 | bnow->next = anow->random; 19 | anow->random = bnow; 20 | } 21 | for(anow = head; anow; anow = anow->next) { 22 | bnow = anow->random; 23 | bnow->random = bnow->next?bnow->next->random:NULL; 24 | } 25 | bhead = head->random; 26 | for(anow = head; anow; anow = anow->next) { 27 | bnow = anow->random; 28 | anow->random = bnow->next; 29 | bnow->next = anow->next?anow->next->random:NULL; 30 | } 31 | return bhead; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /20111101 Add Two Numbers.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | ''' 6 | 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. 7 | 8 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 9 | Output: 7 -> 0 -> 8 10 | ''' 11 | 12 | # Definition for singly-linked list. 13 | # class ListNode: 14 | # def __init__(self, x): 15 | # self.val = x 16 | # self.next = None 17 | 18 | class Solution: 19 | # @return a ListNode 20 | def addTwoNumbers(self, l1, l2): 21 | nHead, flag = ListNode(0), 0 22 | head = nHead 23 | while flag or l1 or l2: 24 | node = ListNode(flag) 25 | if l1: 26 | node.val += l1.val 27 | l1 = l1.next 28 | if l2: 29 | node.val += l2.val 30 | l2 = l2.next 31 | flag = node.val // 10 32 | node.val %= 10 33 | head.next, head = node, node 34 | return nHead.next 35 | 36 | 37 | r1 = ListNode(0) 38 | r2 = ListNode(1) 39 | s = Solution() 40 | s.addTwoNumbers(r1, r2) 41 | -------------------------------------------------------------------------------- /20120422 Remove Duplicates from Sorted List II.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | 6 | ''' 7 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 8 | 9 | For example, 10 | Given 1->2->3->3->4->4->5, return 1->2->5. 11 | Given 1->1->1->2->3, return 2->3. 12 | ''' 13 | # Definition for singly-linked list. 14 | # class ListNode: 15 | # def __init__(self, x): 16 | # self.val = x 17 | # self.next = None 18 | 19 | class Solution: 20 | # @param head, a ListNode 21 | # @return a ListNode 22 | def deleteDuplicates(self, head): 23 | if not head: 24 | return head 25 | nHead, flag = ListNode(0), False 26 | nHead.next, head = head, nHead 27 | while head: 28 | if (head.next and head.next.next and head.next.next.val == head.next.val): 29 | head.next = head.next.next 30 | flag = True 31 | elif flag == True and head.next: 32 | head.next = head.next.next 33 | flag = False 34 | else: 35 | head = head.next 36 | return nHead.next 37 | 38 | 39 | -------------------------------------------------------------------------------- /20120901 Recover Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.left = None 5 | self.right = None 6 | ''' 7 | Two elements of a binary search tree (BST) are swapped by mistake. 8 | 9 | Recover the tree without changing its structure. 10 | 11 | Note: 12 | A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 13 | ''' 14 | 15 | # Definition for a binary tree node 16 | # class TreeNode: 17 | # def __init__(self, x): 18 | # self.val = x 19 | # self.left = None 20 | # self.right = None 21 | 22 | class Solution: 23 | # @param root, a tree node 24 | # @return a tree node 25 | def recoverTree(self, root): 26 | self.pre = None 27 | self.n1 = self.n2 = None 28 | self.dfs(root) 29 | self.n1.val, self.n2.val = self.n2.val, self.n1.val 30 | return root 31 | 32 | def dfs(self, root): 33 | if not root: 34 | return 35 | self.dfs(root.left) 36 | if self.pre and root.val < self.pre.val: 37 | if not self.n1: 38 | self.n1, self.n2 = self.pre, root 39 | else: 40 | self.n2 = root 41 | self.pre = root 42 | self.dfs(root.right) 43 | 44 | 45 | -------------------------------------------------------------------------------- /20120306 Combination Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | The same repeated number may be chosen from C unlimited number of times. 5 | 6 | Note: 7 | All numbers (including target) will be positive integers. 8 | Elements in a combination (a1, a2,... , ak) must be in non-descending order. 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 | class Solution: 17 | # @param candidates, a list of integers 18 | # @param target, integer 19 | # @return a list of lists of integers 20 | def combinationSum(self, candidates, target): 21 | candidates.sort() 22 | self.ans, tmp = [], [] 23 | self.dfs(candidates, target, 0, 0, tmp) 24 | return self.ans 25 | 26 | def dfs(self, candidates, target, p, now, tmp): 27 | if now == target: 28 | self.ans.append(tmp[:]) 29 | return 30 | for i in range(p, len(candidates)): 31 | if now + candidates[i] <= target: 32 | tmp.append(candidates[i]) 33 | self.dfs(candidates, target, i, now+candidates[i], tmp) 34 | tmp.pop() 35 | 36 | -------------------------------------------------------------------------------- /20120430 Partition List.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | 6 | 7 | ''' 8 | 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. 9 | 10 | You should preserve the original relative order of the nodes in each of the two partitions. 11 | 12 | For example, 13 | Given 1->4->3->2->5->2 and x = 3, 14 | return 1->2->2->4->3->5. 15 | ''' 16 | # Definition for singly-linked list. 17 | # class ListNode: 18 | # def __init__(self, x): 19 | # self.val = x 20 | # self.next = None 21 | 22 | class Solution: 23 | # @param head, a ListNode 24 | # @param x, an integer 25 | # @return a ListNode 26 | def partition(self, head, x): 27 | if head is None: 28 | return head 29 | sHead, bHead = ListNode(0), ListNode(0) 30 | sTail, bTail = sHead, bHead 31 | while head is not None: 32 | if head.val < x: 33 | sTail.next = head 34 | sTail = sTail.next 35 | else: 36 | bTail.next = head 37 | bTail = bTail.next 38 | head = head.next 39 | bTail.next = None 40 | sTail.next = bHead.next 41 | return sHead.next 42 | 43 | 44 | -------------------------------------------------------------------------------- /20120302 Search for a Range.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted array of integers, find the starting and ending position of a given target value. 3 | 4 | Your algorithm's runtime complexity must be in the order of O(log n). 5 | 6 | If the target is not found in the array, return [-1, -1]. 7 | 8 | For example, 9 | Given [5, 7, 7, 8, 8, 10] and target value 8, 10 | return [3, 4]. 11 | ''' 12 | 13 | class Solution: 14 | # @param A, a list of integers 15 | # @param target, an integer to be searched 16 | # @return a list of length 2, [index1, index2] 17 | def searchRange(self, A, target): 18 | return [self.lower_bound(A, target), self.upper_bound(A, target)] 19 | 20 | def lower_bound(self, A, target): 21 | l, h, m = 0, len(A), 0 22 | while l < h: 23 | m = (l + h) >> 1 24 | if A[m] < target: 25 | l = m + 1 26 | else: 27 | h = m 28 | return l if l < len(A) and A[l] == target else -1 29 | 30 | 31 | def upper_bound(self, A, target): 32 | l, h, m = 0, len(A), 0 33 | while l < h: 34 | m = (l + h) >> 1 35 | if A[m] <= target: 36 | l = m + 1 37 | else: 38 | h = m 39 | return l-1 if l-1 < len(A) and A[l-1] == target else -1 40 | 41 | 42 | -------------------------------------------------------------------------------- /20120408 Sort Colors.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array with n objects 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. 3 | 4 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 5 | 6 | Note: 7 | You are not suppose to use the library's sort function for this problem. 8 | 9 | click to show follow up. 10 | 11 | Follow up: 12 | A rather straight forward solution is a two-pass algorithm using counting sort. 13 | First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. 14 | 15 | Could you come up with an one-pass algorithm using only constant space? 16 | ''' 17 | 18 | class Solution: 19 | # @param A a list of integers 20 | # @return nothing, sort in place 21 | def sortColors(self, A): 22 | s, t, e = 0, 0, len(A) - 1 23 | while s <= e: 24 | if A[s] == 0: 25 | if s != t: 26 | A[s], A[t] = A[t], A[s] 27 | s, t = s + 1, t + 1 28 | elif A[s] == 1: 29 | s = s + 1 30 | elif A[s] == 2: 31 | if s != e: 32 | A[s], A[e] = A[e], A[s] 33 | e = e - 1 34 | return A 35 | 36 | -------------------------------------------------------------------------------- /20120214 Swap Nodes in Pairs.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | ''' 6 | Given a linked list, swap every two adjacent nodes and return its head. 7 | 8 | For example, 9 | Given 1->2->3->4, you should return the list as 2->1->4->3. 10 | 11 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 12 | ''' 13 | # Definition for singly-linked list. 14 | # class ListNode: 15 | # def __init__(self, x): 16 | # self.val = x 17 | # self.next = None 18 | 19 | class Solution: 20 | # @param a ListNode 21 | # @return a ListNode 22 | def swapPairs(self, head): 23 | if head is None or head.next is None: 24 | return head 25 | nHead = ListNode(0) 26 | nHead.next = head 27 | p1, p2 = nHead, head 28 | while p2 and p2.next: 29 | p2 = p2.next.next 30 | p1.next.next.next = p1.next 31 | p1.next = p1.next.next 32 | p1.next.next.next = p2 33 | p1 = p1.next.next 34 | return nHead.next 35 | 36 | a = ListNode(1) 37 | b = ListNode(2) 38 | c = ListNode(3) 39 | d = ListNode(4) 40 | a.next = b 41 | b.next = c 42 | c.next = d 43 | s = Solution() 44 | x = s.swapPairs(a) 45 | while x: 46 | print x.val 47 | x = x.next -------------------------------------------------------------------------------- /20130218 Sum Root to Leaf Numbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 4 | 5 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 6 | 7 | Find the total sum of all root-to-leaf numbers. 8 | 9 | For example, 10 | 11 | 1 12 | / \ 13 | 2 3 14 | 15 | The root-to-leaf path 1->2 represents the number 12. 16 | The root-to-leaf path 1->3 represents the number 13. 17 | 18 | Return the sum = 12 + 13 = 25. 19 | */ 20 | /** 21 | * Definition for binary tree 22 | * struct TreeNode { 23 | * int val; 24 | * TreeNode *left; 25 | * TreeNode *right; 26 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | int sumNumbers(TreeNode *root) { 32 | // IMPORTANT: Please reset any member data you declared, as 33 | // the same Solution instance will be reused for each test case. 34 | int ans = 0; 35 | if (!root) return 0; 36 | dfsTree(root, root->val, ans); 37 | return ans; 38 | } 39 | void dfsTree(TreeNode *fa, int now, int &ans) { 40 | if (!(fa->left || fa->right)) ans += now; 41 | else { 42 | if (fa->left) dfsTree(fa->left, now*10+fa->left->val, ans); 43 | if (fa->right)dfsTree(fa->right,now*10+fa->right->val,ans); 44 | } 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /20120928 Binary Tree Zigzag Level Order Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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). 3 | 4 | For example: 5 | Given binary tree {3,9,20,#,#,15,7}, 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its zigzag level order traversal as: 12 | [ 13 | [3], 14 | [20,9], 15 | [15,7] 16 | ] 17 | confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. 18 | 19 | 20 | */ 21 | /** 22 | * Definition for binary tree 23 | * struct TreeNode { 24 | * int val; 25 | * TreeNode *left; 26 | * TreeNode *right; 27 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 28 | * }; 29 | */ 30 | class Solution { 31 | public: 32 | vector > vec; 33 | vector > zigzagLevelOrder(TreeNode *root) { 34 | vec.clear(); 35 | dfs(root, 0, vec); 36 | for (int i = 1; i < vec.size(); i += 2) 37 | reverse(vec[i].begin(), vec[i].end()); 38 | return vec; 39 | } 40 | void dfs(TreeNode *root, int dep, vector > &vec) { 41 | if (root == NULL) return; 42 | if (vec.size() <= dep) vec.push_back(vector()); 43 | vec[dep].push_back(root->val); 44 | dfs(root->left, dep+1, vec); 45 | dfs(root->right, dep+1, vec); 46 | } 47 | }; -------------------------------------------------------------------------------- /20121014 Flatten Binary Tree to Linked List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, flatten it to a linked list in-place. 3 | 4 | For example, 5 | Given 6 | 7 | 1 8 | / \ 9 | 2 5 10 | / \ \ 11 | 3 4 6 12 | The flattened tree should look like: 13 | 1 14 | \ 15 | 2 16 | \ 17 | 3 18 | \ 19 | 4 20 | \ 21 | 5 22 | \ 23 | 6 24 | click to show hints. 25 | 26 | Hints: 27 | If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. 28 | 29 | Discuss 30 | 31 | 32 | */ 33 | /** 34 | * Definition for binary tree 35 | * struct TreeNode { 36 | * int val; 37 | * TreeNode *left; 38 | * TreeNode *right; 39 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 40 | * }; 41 | */ 42 | class Solution { 43 | public: 44 | void flatten(TreeNode *root) { 45 | now = root; 46 | dfs(root); 47 | } 48 | TreeNode *now; 49 | void dfs(TreeNode *root) { 50 | if (!root) return; 51 | TreeNode *right = root->right; 52 | if (root->left) { 53 | now = now->right = root->left; 54 | dfs(root->left); 55 | } 56 | root->left = NULL; 57 | if (right) { 58 | now = now->right = right; 59 | dfs(right); 60 | } 61 | } 62 | }; -------------------------------------------------------------------------------- /20120315 Wildcard Matching.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement wildcard pattern matching with support for '?' and '*'. 3 | 4 | '?' Matches any single character. 5 | '*' Matches any sequence of characters (including the empty sequence). 6 | 7 | The matching should cover the entire input string (not partial). 8 | 9 | The function prototype should be: 10 | bool isMatch(const char *s, const char *p) 11 | 12 | Some examples: 13 | isMatch("aa","a") -> false 14 | isMatch("aa","aa") -> true 15 | isMatch("aaa","aa") -> false 16 | isMatch("aa", "*") -> true 17 | isMatch("aa", "a*") -> true 18 | isMatch("ab", "?*") -> true 19 | isMatch("aab", "c*a*b") -> false 20 | ''' 21 | 22 | class Solution: 23 | # @param s, an input string 24 | # @param p, a pattern string 25 | # @return a boolean 26 | def isMatch(self, s, p): 27 | ps, pp, lastp, lasts = 0, 0, -1, -1 28 | while ps < len(s): 29 | if pp < len(p) and (s[ps] == p[pp] or p[pp] == '?'): 30 | ps, pp = ps + 1, pp + 1 31 | elif pp < len(p) and p[pp] == '*': 32 | pp = pp + 1 33 | lastp, lasts = pp, ps 34 | elif lastp != -1: 35 | lasts = lasts + 1 36 | pp, ps = lastp, lasts 37 | else: 38 | return False 39 | while pp < len(p) and p[pp] == '*': 40 | pp = pp + 1 41 | return ps == len(s) and pp == len(p) 42 | 43 | 44 | -------------------------------------------------------------------------------- /20120403 Simplify Path.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an absolute path for a file (Unix-style), simplify it. 3 | 4 | For example, 5 | path = "/home/", => "/home" 6 | path = "/a/./b/../../c/", => "/c" 7 | click to show corner cases. 8 | 9 | Corner Cases: 10 | Did you consider the case where path = "/../"? 11 | In this case, you should return "/". 12 | Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 13 | In this case, you should ignore redundant slashes and return "/home/foo". 14 | */ 15 | class Solution { 16 | public: 17 | string simplifyPath(string path) { 18 | //cout << "here" << endl; 19 | vector resVec; 20 | string ans = ""; 21 | int pos = 0, rpos; 22 | while ((rpos = path.find("/", pos+1)) != string::npos) { 23 | resVec.push_back(path.substr(pos, rpos-pos)); 24 | cal(resVec); 25 | pos = rpos; 26 | } 27 | resVec.push_back(path.substr(pos)); 28 | cal(resVec); 29 | if (resVec.size() == 0) resVec.push_back("/"); 30 | for (auto &s: resVec) ans.append(s); 31 | return ans; 32 | } 33 | void cal(vector &vec) { 34 | string s = vec[vec.size() - 1]; 35 | if (s == "/" || s == "/.") { 36 | vec.pop_back(); 37 | } else if (s == "/..") { 38 | vec.pop_back(); 39 | if (vec.size()) vec.pop_back(); 40 | } 41 | } 42 | }; -------------------------------------------------------------------------------- /20120827 Unique Binary Search Trees II.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.left = None 5 | self.right = None 6 | 7 | 8 | ''' 9 | Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. 10 | 11 | For example, 12 | Given n = 3, your program should return all 5 unique BST's shown below. 13 | 14 | 1 3 3 2 1 15 | \ / / / \ \ 16 | 3 2 1 1 3 2 17 | / / \ \ 18 | 2 1 2 3 19 | ''' 20 | # Definition for a binary tree node 21 | # class TreeNode: 22 | # def __init__(self, x): 23 | # self.val = x 24 | # self.left = None 25 | # self.right = None 26 | 27 | class Solution: 28 | # @return a list of tree node 29 | treelist = None 30 | def generateTrees(self, n): 31 | return self.dfs(0, n) 32 | 33 | def dfs(self, l, r): 34 | ans = [] 35 | if l == r: 36 | ans.append(None) 37 | return ans 38 | for i in range(l, r): 39 | lb, rb = self.dfs(l, i), self.dfs(i + 1, r) 40 | for lc in lb: 41 | for rc in rb: 42 | node = TreeNode(i + 1) 43 | node.left = lc 44 | node.right = rc 45 | ans.append(node) 46 | return ans 47 | 48 | -------------------------------------------------------------------------------- /20120415 Minimum Window Substring.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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). 3 | 4 | For example, 5 | S = "ADOBECODEBANC" 6 | T = "ABC" 7 | Minimum window is "BANC". 8 | 9 | Note: 10 | If there is no such window in S that covers all characters in T, return the emtpy string "". 11 | 12 | If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. 13 | ''' 14 | 15 | class Solution: 16 | # @return a string 17 | def minWindow(self, S, T): 18 | d, dt = {}, dict.fromkeys(T, 0) 19 | for c in T: d[c] = d.get(c, 0) + 1 20 | pi, pj, cont = 0, 0, 0 21 | ans = "" 22 | while pj < len(S): 23 | if S[pj] in dt: 24 | if dt[S[pj]] < d[S[pj]]: 25 | cont += 1 26 | dt[S[pj]] += 1; 27 | if cont == len(T): 28 | while pi < pj: 29 | if S[pi] in dt: 30 | if dt[S[pi]] == d[S[pi]]: 31 | break; 32 | dt[S[pi]] -= 1; 33 | pi+= 1 34 | if ans == '' or pj - pi < len(ans): 35 | ans = S[pi:pj+1] 36 | dt[S[pi]] -= 1 37 | pi += 1 38 | cont -= 1 39 | pj += 1 40 | return ans 41 | 42 | -------------------------------------------------------------------------------- /20130930 Candy.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There are N children standing in a line. Each child is assigned a rating value. 3 | 4 | You are giving candies to these children subjected to the following requirements: 5 | 6 | Each child must have at least one candy. 7 | Children with a higher rating get more candies than their neighbors. 8 | What is the minimum candies you must give? 9 | */ 10 | class Solution { 11 | public: 12 | int candy(vector &ratings) { 13 | // IMPORTANT: Please reset any member data you declared, as 14 | // the same Solution instance will be reused for each test case. 15 | int size = ratings.size(), ans = 0; 16 | if (size == 1) return 1; 17 | vector candies(size, 1); 18 | for (int i = 0; i < size; i++) { 19 | if (i == 0 && ratings[i] <= ratings[i + 1] || 20 | i == size - 1 && ratings[i] <= ratings[i - 1] || 21 | ratings[i] <= ratings[i + 1] && ratings[i] <= ratings[i - 1]) { 22 | for (int j = i - 1; j >=0 && ratings[j] > ratings[j + 1]; j--) 23 | candies[j] = max(candies[j], candies[j + 1] + 1); 24 | for (int j = i + 1; j < size && ratings[j] > ratings[j - 1]; j++) 25 | candies[j] = max(candies[j], candies[j - 1] + 1); 26 | } 27 | } 28 | //for (int i = 0; i < size; i++) printf("%d ", candies[i]); 29 | for (int i = 0; i < size; i++) ans += candies[i]; 30 | return ans; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /20120627 Reverse Linked List II.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | # Definition for singly-linked list. 3 | class ListNode: 4 | def __init__(self, x): 5 | self.val = x 6 | self.next = None 7 | 8 | ''' 9 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 10 | 11 | For example: 12 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 13 | 14 | return 1->4->3->2->5->NULL. 15 | 16 | Note: 17 | Given m, n satisfy the following condition: 18 | 1 <= m <= n <= len(list) 19 | ''' 20 | # Definition for singly-linked list. 21 | # class ListNode: 22 | # def __init__(self, x): 23 | # self.val = x 24 | # self.next = None 25 | 26 | class Solution: 27 | # @param head, a ListNode 28 | # @param m, an integer 29 | # @param n, an integer 30 | # @return a ListNode 31 | def reverseBetween(self, head, m, n): 32 | prem, pre, next, now, nowm = None, None, None, head, None; 33 | ind = 1; 34 | while now is not None: 35 | next = now.next 36 | if ind >= m and ind <= n: 37 | now.next = pre 38 | if ind == m: 39 | prem, nowm = pre, now 40 | if ind == n: 41 | nowm.next = next 42 | if prem is None: 43 | head = now 44 | else: 45 | prem.next = now 46 | pre, now, ind = now, next, ind + 1 47 | return head 48 | 49 | -------------------------------------------------------------------------------- /20120405 Set Matrix Zeroes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 3 | 4 | click to show follow up. 5 | 6 | Follow up: 7 | Did you use extra space? 8 | A straight forward solution using O(mn) space is probably a bad idea. 9 | A simple improvement uses O(m + n) space, but still not the best solution. 10 | Could you devise a constant space solution? 11 | ''' 12 | 13 | class Solution: 14 | # @param matrix, a list of lists of integers 15 | # RETURN NOTHING, MODIFY matrix IN PLACE. 16 | def setZeroes(self, matrix): 17 | if len(matrix) == 0: 18 | return 19 | lenn, lenm = len(matrix), len(matrix[0]) 20 | x, y = None, None 21 | for i in range(lenn): 22 | for j in range(lenm): 23 | if matrix[i][j] != 0: 24 | continue 25 | if x is not None: 26 | matrix[x][j] = matrix[i][y] = 0 27 | else: 28 | x, y = i, j 29 | if x is None: 30 | return 31 | for i in range(lenn): 32 | for j in range(lenm): 33 | if i == x or j == y: 34 | continue 35 | if matrix[x][j] == 0 or matrix[i][y] == 0: 36 | matrix[i][j] = 0 37 | for i in range(lenn): 38 | matrix[i][y] = 0 39 | for i in range(lenm): 40 | matrix[x][i] = 0 41 | 42 | -------------------------------------------------------------------------------- /20121028 Populating Next Right Pointers in Each Node.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree 3 | 4 | struct TreeLinkNode { 5 | TreeLinkNode *left; 6 | TreeLinkNode *right; 7 | TreeLinkNode *next; 8 | } 9 | 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. 10 | 11 | Initially, all next pointers are set to NULL. 12 | 13 | Note: 14 | 15 | You may only use constant extra space. 16 | You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). 17 | For example, 18 | Given the following perfect binary tree, 19 | 1 20 | / \ 21 | 2 3 22 | / \ / \ 23 | 4 5 6 7 24 | After calling your function, the tree should look like: 25 | 1 -> NULL 26 | / \ 27 | 2 -> 3 -> NULL 28 | / \ / \ 29 | 4->5->6->7 -> NULL 30 | */ 31 | /** 32 | * Definition for binary tree with next pointer. 33 | * struct TreeLinkNode { 34 | * int val; 35 | * TreeLinkNode *left, *right, *next; 36 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 37 | * }; 38 | */ 39 | class Solution { 40 | public: 41 | void connect(TreeLinkNode *root) { 42 | if (root == NULL) return; 43 | connect(root->left); 44 | connect(root->right); 45 | for (TreeLinkNode *nl = root->left, *nr = root->right; nl; 46 | nl->next = nr, nl = nl->right, nr = nr->left); 47 | } 48 | }; -------------------------------------------------------------------------------- /20120306 Combination Sum II.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | Each number in C may only be used once in the combination. 5 | 6 | Note: 7 | All numbers (including target) will be positive integers. 8 | Elements in a combination (a1, a2, ... , ak) must be in non-descending order. 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 | class Solution: 19 | # @param candidates, a list of integers 20 | # @param target, integer 21 | # @return a list of lists of integers 22 | def combinationSum2(self, candidates, target): 23 | candidates.sort() 24 | self.ans, tmp, use = [], [], [0] * len(candidates) 25 | self.dfs(candidates, target, 0, 0, tmp, use) 26 | return self.ans 27 | 28 | def dfs(self, can, target, p, now, tmp, use): 29 | if now == target: 30 | self.ans.append(tmp[:]) 31 | return 32 | for i in range(p, len(can)): 33 | if now + can[i] <= target and (i == 0 or can[i] != can[i-1] or use[i-1] == 1): 34 | tmp.append(can[i]); 35 | use[i] = 1 36 | self.dfs(can, target, i+1, now + can[i], tmp, use) 37 | tmp.pop() 38 | use[i] = 0 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /20131116 Sort List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *sortList(ListNode *head) { 12 | // IMPORTANT: Please reset any member data you declared, as 13 | // the same Solution instance will be reused for each test case. 14 | if (head == NULL) return head; 15 | ListNode *tail = head; 16 | int size = 0; 17 | for (; tail!= NULL; tail = tail->next, size++); 18 | MergeSort(head, tail, size); 19 | return head; 20 | } 21 | void MergeSort(ListNode *l, ListNode *r, int size) { 22 | if (l->next == r) return; 23 | ListNode *m = l; 24 | for (int i = 0; i < size / 2; i++, m = m->next); 25 | MergeSort(l, m, size / 2); 26 | MergeSort(m, r, size - size / 2); 27 | ListNode *lp = l, *rp = m, *s; 28 | if (l->val > m-> val) { 29 | swap(l->val, m->val); 30 | for (ListNode *t = m; t->next != r && t->val > t->next->val; 31 | swap(t->val, t->next->val), t = t->next); 32 | } 33 | s = lp, lp = lp->next; 34 | for (int i = 1; i < size; i++) { 35 | if (rp == r || (lp !=m && lp->val < rp->val)) 36 | s->next = lp, lp = lp->next; 37 | else 38 | s->next = rp, rp = rp->next; 39 | s = s->next; 40 | } 41 | s->next = r; 42 | } 43 | void swap (int &x, int &y) { 44 | x^=y^=x^=y; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /20120923 Symmetric Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 3 | 4 | For example, this binary tree is symmetric: 5 | 6 | 1 7 | / \ 8 | 2 2 9 | / \ / \ 10 | 3 4 4 3 11 | But the following is not: 12 | 1 13 | / \ 14 | 2 2 15 | \ \ 16 | 3 3 17 | */ 18 | /** 19 | * Definition for binary tree 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | bool isSymmetric(TreeNode *root) { 30 | vector now, next; 31 | if (root) now.push_back(root); 32 | bool flag = true; 33 | while(now.size() > 0) { 34 | next.clear(); 35 | int size = now.size(); 36 | for (int l = 0, r = size - 1; l <= r; l++, r--) { 37 | if (!nodeeql(now[l]->left, now[r]->right) || 38 | !nodeeql(now[l]->right, now[r]->left)) 39 | flag = false; 40 | } 41 | if (!flag) break; 42 | for (int i = 0; i < size; i++) { 43 | if (now[i]->left) next.push_back(now[i]->left); 44 | if (now[i]->right)next.push_back(now[i]->right); 45 | } 46 | now = next; 47 | } 48 | return flag; 49 | } 50 | bool nodeeql(TreeNode *l1, TreeNode *l2) { 51 | if ((!l1 && l2) || (l1 && !l2)) return false; 52 | return !l1 && !l2 || l1->val == l2->val; 53 | } 54 | }; -------------------------------------------------------------------------------- /20130227 Palindrome Partitioning.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return all possible palindrome partitioning of s. 5 | 6 | For example, given s = "aab", 7 | Return 8 | 9 | [ 10 | ["aa","b"], 11 | ["a","a","b"] 12 | ] 13 | 14 | */ 15 | 16 | class Solution { 17 | public: 18 | vector > vecResult; 19 | vector > partition(string s) { 20 | // IMPORTANT: Please reset any member data you declared, as 21 | // the same Solution instance will be reused for each test case. 22 | vecResult.clear(); 23 | vector vecStr; 24 | vector > parStart(s.length()); 25 | for (int i = 0; i < s.length(); i++) { 26 | for (int j = i; 2*i-j < s.length() && j >= 0 && s[j] == s[2*i-j]; j--) 27 | parStart[j].push_back(s.substr(j, 2*i-2*j+1)); 28 | for (int j = i; 2*i-j+1 < s.length() && j >= 0 && s[j] == s[2*i-j+1]; j--) 29 | parStart[j].push_back(s.substr(j, 2*i-2*j+2)); 30 | } 31 | dfs(parStart, vecStr, 0, s.length()); 32 | return vecResult; 33 | } 34 | void dfs(vector > &parStart, vector &vecStr, int sp, int ep) { 35 | if (sp == ep) { 36 | vecResult.push_back(vecStr); 37 | } else { 38 | for (int i = 0; i < parStart[sp].size(); i++) { 39 | vecStr.push_back(parStart[sp][i]); 40 | dfs(parStart, vecStr, sp + parStart[sp][i].length(), ep); 41 | vecStr.pop_back(); 42 | } 43 | } 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /20121014 Path Sum II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 3 | 4 | For example: 5 | Given the below binary tree and sum = 22, 6 | 5 7 | / \ 8 | 4 8 9 | / / \ 10 | 11 13 4 11 | / \ / \ 12 | 7 2 5 1 13 | return 14 | [ 15 | [5,4,11,2], 16 | [5,8,4,5] 17 | ] 18 | */ 19 | /** 20 | * Definition for binary tree 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | class Solution { 29 | public: 30 | vector > ans; 31 | vector path; 32 | vector > pathSum(TreeNode *root, int sum) { 33 | ans.clear(); 34 | path.clear(); 35 | if (root) dfs(root, 0, sum) ; 36 | return ans; 37 | } 38 | void dfs(TreeNode *node, int now, int sum) { 39 | if (node ->left == NULL && node->right == NULL) { 40 | if (now + node->val == sum) { 41 | path.push_back(node->val); 42 | ans.push_back(path); 43 | path.pop_back(); 44 | } 45 | return; 46 | } 47 | if (node->left) { 48 | path.push_back(node->val); 49 | dfs(node->left, now + node->val, sum); 50 | path.pop_back(); 51 | } 52 | if (node->right) { 53 | path.push_back(node->val); 54 | dfs(node->right, now + node->val, sum); 55 | path.pop_back(); 56 | } 57 | } 58 | }; -------------------------------------------------------------------------------- /20120418 Word Search.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a 2D board and a word, find if the word exists in the grid. 3 | 4 | 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. 5 | 6 | For example, 7 | Given board = 8 | 9 | [ 10 | ["ABCE"], 11 | ["SFCS"], 12 | ["ADEE"] 13 | ] 14 | word = "ABCCED", -> returns true, 15 | word = "SEE", -> returns true, 16 | word = "ABCB", -> returns false. 17 | ''' 18 | 19 | class Solution: 20 | # @param board, a list of lists of 1 length string 21 | # @param word, a string 22 | # @return a boolean 23 | 24 | def exist(self, board, word): 25 | self.h = len(board) 26 | self.w = len(board[0]) 27 | for i in range(self.h): 28 | for j in range(self.w): 29 | if board[i][j] == word[0]: 30 | t, board[i][j] = board[i][j], ' ' 31 | if self.dfs(board, word, i, j, 1): 32 | return True 33 | board[i][j] = t 34 | return False 35 | 36 | def dfs(self, board, word, x, y, p): 37 | dx, dy = [1, -1, 0, 0], [0, 0, 1, -1] 38 | if (p == len(word)): 39 | return True 40 | for i in range(4): 41 | nx, ny = x + dx[i], y + dy[i] 42 | if 0 <= nx and nx < self.h and 0 <= ny and ny < self.w and board[nx][ny] == word[p]: 43 | t, board[nx][ny] = board[nx][ny], ' ' 44 | if self.dfs(board, word, nx, ny, p + 1): 45 | return True 46 | board[nx][ny] = t 47 | return False 48 | 49 | -------------------------------------------------------------------------------- /20130210 Word Ladder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: 3 | 4 | Only one letter can be changed at a time 5 | Each intermediate word must exist in the dictionary 6 | For example, 7 | 8 | Given: 9 | start = "hit" 10 | end = "cog" 11 | dict = ["hot","dot","dog","lot","log"] 12 | As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", 13 | return its length 5. 14 | 15 | Note: 16 | Return 0 if there is no such transformation sequence. 17 | All words have the same length. 18 | All words contain only lowercase alphabetic characters. 19 | */ 20 | 21 | class Solution { 22 | public: 23 | int ladderLength(string start, string end, unordered_set &dict) { 24 | // IMPORTANT: Please reset any member data you declared, as 25 | // the same Solution instance will be reused for each test case. 26 | queue q; 27 | unordered_map vis; 28 | int len = start.length(); 29 | q.push(start); 30 | vis[start] = 1; 31 | while (!q.empty()) { 32 | string s = q.front(); q.pop(); 33 | int step = vis[s]; 34 | for (int i = 0; i < len; i++) { 35 | string news = s; 36 | for (char c = 'a'; c <= 'z'; c++) { 37 | if (s[i] == c) continue; 38 | news[i] = c; 39 | if (news == end) return step + 1; 40 | if (dict.count(news) && !vis[news]) { 41 | vis[news] = step + 1; 42 | q.push(news); 43 | } 44 | } 45 | } 46 | } 47 | return 0; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /20120126 4Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. 3 | 4 | Note: 5 | Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a <= b <= c <= d) 6 | The solution set must not contain duplicate quadruplets. 7 | For example, given array S = {1 0 -1 0 -2 2}, and target = 0. 8 | 9 | A solution set is: 10 | (-1, 0, 0, 1) 11 | (-2, -1, 1, 2) 12 | (-2, 0, 0, 2) 13 | */ 14 | #include 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | class Solution { 20 | public: 21 | vector > fourSum(vector &num, int target) { 22 | vector > ans; 23 | sort(num.begin(), num.end()); 24 | for (int i = 0; i < num.size(); i++) { 25 | if (i > 0 && num[i] == num[i-1]) continue; 26 | for (int j = i + 1; j < num.size(); j++) { 27 | if (j > i + 1 && num[j] == num[j - 1]) continue; 28 | int l = j + 1, r = num.size() - 1; 29 | while (l < r) { 30 | int sum = num[i] + num[j] + num[l] + num[r]; 31 | if (sum == target) { 32 | ans.push_back({num[i], num[j], num[l], num[r]}); 33 | while (l < r && num[l] == num[l + 1]) l++; l++; 34 | while (l < r && num[r] == num[r - 1]) r--; r--; 35 | } else if (sum < target) { 36 | l++; 37 | } else { 38 | r--; 39 | } 40 | } 41 | } 42 | } 43 | return ans; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /20120327 Insert Interval.py: -------------------------------------------------------------------------------- 1 | 2 | class Interval: 3 | def __init__(self, s=0, e=0): 4 | self.start = s 5 | self.end = e 6 | ''' 7 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 8 | 9 | You may assume that the intervals were initially sorted according to their start times. 10 | 11 | Example 1: 12 | Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. 13 | 14 | Example 2: 15 | Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. 16 | 17 | This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. 18 | ''' 19 | 20 | # Definition for an interval. 21 | # class Interval: 22 | # def __init__(self, s=0, e=0): 23 | # self.start = s 24 | # self.end = e 25 | 26 | class Solution: 27 | # @param intervals, a list of Intervals 28 | # @param newInterval, a Interval 29 | # @return a list of Interval 30 | def insert(self, intervals, newInterval): 31 | ans, inserted = [], False 32 | for i in range(len(intervals)): 33 | if intervals[i].end < newInterval.start: 34 | ans.append(intervals[i]) 35 | elif intervals[i].start > newInterval.end: 36 | if not inserted: 37 | inserted = True 38 | ans.append(newInterval) 39 | ans.append(intervals[i]) 40 | else: 41 | newInterval.start = min(newInterval.start, intervals[i].start) 42 | newInterval.end = max(newInterval.end, intervals[i].end) 43 | if len(ans) == 0 or newInterval.start > ans[-1].end: 44 | ans.append(newInterval) 45 | return ans 46 | 47 | 48 | -------------------------------------------------------------------------------- /20130221 Surrounded Regions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. 3 | 4 | A region is captured by flipping all 'O's into 'X's in that surrounded region . 5 | 6 | For example, 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 | class Solution { 19 | public: 20 | void solve(vector > &board) { 21 | // IMPORTANT: Please reset any member data you declared, as 22 | // the same Solution instance will be reused for each test case. 23 | queue > q; 24 | int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1}; 25 | if (board.size() == 0) return ; 26 | int lenh = board.size(), lenw = board[0].size(); 27 | for (int i = 0; i < lenh; i++) 28 | for (int j = 0; j < lenw; j++) 29 | if ((i == 0 || j == 0 || i == lenh - 1 || j == lenw - 1) 30 | && board[i][j] == 'O') { 31 | board[i][j] = 'Y'; 32 | q.push(make_pair(i, j)); 33 | } 34 | while (!q.empty()) { 35 | pair p = q.front(); q.pop(); 36 | for (int i = 0; i < 4; i++) { 37 | int ni = p.first + dx[i], nj = p.second + dy[i]; 38 | if (ni >= 0 && ni < lenh && nj >= 0 && nj < lenw 39 | && board[ni][nj] == 'O') { 40 | board[ni][nj] = 'Y'; 41 | q.push(make_pair(ni, nj)); 42 | } 43 | } 44 | } 45 | for (int i = 0; i < lenh; i++) 46 | for (int j = 0; j < lenw; j++) 47 | board[i][j] = (board[i][j] == 'Y' ? 'O' : 'X'); 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /20131109 LRU Cache.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node{ 4 | public: 5 | int key, val; 6 | Node *pre, *next; 7 | Node(int k, int v): key(k), val(v), pre(NULL), next(NULL) {} 8 | }; 9 | class LRUCache{ 10 | map mp; 11 | map::iterator iter; 12 | int used, cap; 13 | Node *head, *tail; 14 | public: 15 | LRUCache(int capacity) { 16 | mp.clear(); 17 | used = 0, cap = capacity; 18 | head = new Node(0, 0); 19 | tail = new Node(0, 0); 20 | head->next = tail, tail->pre = head; 21 | } 22 | ~LRUCache(){ 23 | for (Node *n = head, *nnext; n; n = nnext) { 24 | nnext = n->next; 25 | delete n; 26 | } 27 | } 28 | 29 | int get(int key) { 30 | if ((iter = mp.find(key)) != mp.end()) { 31 | movetoFirst(iter->second); 32 | return iter->second->val; 33 | }else 34 | return -1; 35 | } 36 | 37 | void set(int key, int value) { 38 | if ((iter = mp.find(key)) != mp.end()) { 39 | iter->second->val = value; 40 | movetoFirst(iter->second); 41 | } else { 42 | Node *node; 43 | if (used == cap) { 44 | mp.erase(tail->pre->key); 45 | node = tail->pre; 46 | node->key = key, node->val = value; 47 | } else { 48 | node = new Node(key, value); 49 | used++; 50 | } 51 | mp[node->key] = node; 52 | movetoFirst(node); 53 | } 54 | } 55 | void movetoFirst(Node *node) { 56 | if (node->pre && node->next) { 57 | node->pre->next = node->next; 58 | node->next->pre = node->pre; 59 | } 60 | node->pre = head, node->next = head->next; 61 | head->next->pre = node, head->next = node; 62 | } 63 | 64 | }; 65 | -------------------------------------------------------------------------------- /20120304 Sudoku Solver.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program to solve a Sudoku puzzle by filling the empty cells. 3 | 4 | Empty cells are indicated by the character '.'. 5 | 6 | You may assume that there will be only one unique solution. 7 | ''' 8 | class Solution: 9 | # @param board, a 9x9 2D array 10 | # Solve the Sudoku by modifying the input board in-place. 11 | # Do not return any value. 12 | def solveSudoku(self, board): 13 | lt, rt, bt = [0] * 9, [0] * 9, [0] * 9 14 | self.dt = {} 15 | for i in range(9): self.dt[1< true 6 | " 0.1 " => true 7 | "abc" => false 8 | "1 a" => false 9 | "2e10" => true 10 | Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. 11 | ''' 12 | 13 | class Solution: 14 | # @param s, a string 15 | # @return a boolean 16 | def isNumber(self, s): 17 | s = s.strip(); 18 | # dfa status 19 | err = -1 # error 20 | srt = 0 # start 21 | sgd = 1 # integer part sign 22 | did = 2 # integer part number 23 | ddp = 3 # xx. (there are some numbers before '.') 24 | dnp = 3 # . 25 | dii = 5 # decimal part number 26 | exe = 6 # e 27 | sge = 7 # exp part sign 28 | die = 8 # exp part number 29 | end = 9 # end 30 | # construct a dfa 31 | dfa = [[err] * 128 for i in range(9)] 32 | dfa[srt][ord('+')] = dfa[srt][ord('-')] = sgd 33 | dfa[srt][ord('.')] = dfa[sgd][ord('.')] = dnp 34 | dfa[did][ord('.')] = ddp 35 | dfa[did][ord('e')] = dfa[ddp][ord('e')] = dfa[dii][ord('e')] = exe 36 | dfa[exe][ord('+')] = dfa[exe][ord('-')] = sge 37 | dfa[dii][0] = dfa[ddp][0] = dfa[did][0] = dfa[die][0] = end 38 | for i in range(10): 39 | t = ord('0') + i 40 | dfa[srt][t] = dfa[sgd][t] = dfa[did][t] = did 41 | dfa[ddp][t] = dfa[dnp][t] = dfa[dii][t] = dii 42 | dfa[exe][t] = dfa[sge][t] = dfa[die][t] = die 43 | # run dfa with s 44 | s = s.strip() 45 | status = srt 46 | for c in s: 47 | status = dfa[status][ord(c)] 48 | #print status 49 | if (status == err): 50 | return False 51 | return True if dfa[status][0] == end else False 52 | 53 | 54 | -------------------------------------------------------------------------------- /20121028 Populating Next Right Pointers in Each Node II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Follow up for problem "Populating Next Right Pointers in Each Node". 3 | 4 | What if the given tree could be any binary tree? Would your previous solution still work? 5 | 6 | Note: 7 | 8 | You may only use constant extra space. 9 | For example, 10 | Given the following binary tree, 11 | 1 12 | / \ 13 | 2 3 14 | / \ \ 15 | 4 5 7 16 | After calling your function, the tree should look like: 17 | 1 -> NULL 18 | / \ 19 | 2 -> 3 -> NULL 20 | / \ \ 21 | 4-> 5 -> 7 -> NULL 22 | */ 23 | /** 24 | * Definition for binary tree with next pointer. 25 | * struct TreeLinkNode { 26 | * int val; 27 | * TreeLinkNode *left, *right, *next; 28 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 29 | * }; 30 | */ 31 | class Solution { 32 | public: 33 | TreeLinkNode *next(TreeLinkNode* p) { 34 | while (p && !p->left && !p->right) p = p->next; 35 | return p; 36 | } 37 | void connect(TreeLinkNode *root) { 38 | TreeLinkNode *nextHead, *preHead, *nextPreHead; 39 | for (TreeLinkNode *head = root; head; preHead = head, head = nextHead) { 40 | head = next(head); 41 | if (head != NULL) 42 | nextHead = head->left ? head->left : head->right; 43 | else 44 | break; 45 | for (preHead = NULL; head; preHead = head, head = next(head->next)) { 46 | if (head->left && head->right) head->left->next = head->right; 47 | if (preHead) { 48 | nextPreHead = head->left ? head->left : head->right; 49 | if (preHead->right == NULL) 50 | preHead->left->next = nextPreHead; 51 | else 52 | preHead->right->next = nextPreHead; 53 | } 54 | } 55 | } 56 | } 57 | }; -------------------------------------------------------------------------------- /20120108 Regular Expression Matching.py: -------------------------------------------------------------------------------- 1 | ''' 2 | '.' Matches any single character. 3 | '*' Matches zero or more of the preceding element. 4 | 5 | The matching should cover the entire input string (not partial). 6 | 7 | The function prototype should be: 8 | bool isMatch(const char *s, const char *p) 9 | 10 | Some examples: 11 | isMatch("aa","a") -> false 12 | isMatch("aa","aa") -> true 13 | isMatch("aaa","aa") -> false 14 | isMatch("aa", "a*") -> true 15 | isMatch("aa", ".*") -> true 16 | isMatch("ab", ".*") -> true 17 | isMatch("aab", "c*a*b") -> true 18 | ''' 19 | 20 | class Solution: 21 | # @return a boolean 22 | def isMatch(self, s, p): 23 | s, p = ' ' + s, ' ' + p 24 | dp = [[False] * (len(p)) for i in range(len(s))] 25 | dp[0][0] = True 26 | ind = 2 27 | while ind < len(p) and p[ind] == '*': 28 | dp[0][ind], ind = True, ind + 2 29 | for i in range(1, len(s)): 30 | for j in range(1, len(p)): 31 | if (s[i] == p[j] or p[j] == '.') and dp[i-1][j-1]: 32 | dp[i][j] = True 33 | if p[j] == '*' and (dp[i][j-2] or ((p[j-1] == '.' or p[j-1] == s[i]) and (dp[i-1][j-2] or dp[i-1][j]))): 34 | dp[i][j] = True 35 | return dp[len(s) - 1][len(p) - 1] 36 | 37 | s = Solution() 38 | print s.isMatch("aa", "a") # False 39 | print s.isMatch("aa", "aa") # True 40 | print s.isMatch("aaa","aa") # False 41 | print s.isMatch("aa", "a*") # True 42 | print s.isMatch("aa", ".*") # True 43 | print s.isMatch("ab", ".*") # True 44 | print s.isMatch("aab", "c*a*b") # True 45 | print s.isMatch("aaa", "ab*a") # Fasle 46 | print s.isMatch("aaba", "ab*a*c*a") # False 47 | print s.isMatch("", ".*") # True 48 | print s.isMatch("bbab", "b*a*") # False 49 | print s.isMatch("aab", "b.*") # False 50 | 51 | 52 | -------------------------------------------------------------------------------- /20120223 Substring with Concatenation of All Words.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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 concatenation of each word in L exactly once and without any intervening characters. 3 | 4 | For example, given: 5 | S: "barfoothefoobarman" 6 | L: ["foo", "bar"] 7 | 8 | You should return the indices: [0,9]. 9 | (order does not matter). 10 | ''' 11 | 12 | class Solution: 13 | # @param S, a string 14 | # @param L, a list of string 15 | # @return a list of integer 16 | def findSubstring(self, S, L): 17 | LS, LL, LL0 = len(S), len(L), len(L[0]) 18 | did, ids, dl = {}, 0, {} 19 | for s in L: 20 | id = did.get(s, -1) 21 | if id == -1: 22 | ids = ids + 1 23 | id = ids 24 | did[s] = id 25 | dl[id] = dl.get(id, 0) + 1 26 | 27 | pos, ans = [0] * LS, [] 28 | for k, v in did.items(): 29 | f = S.find(k) 30 | while f != -1: 31 | pos[f] = v 32 | f = S.find(k, f + 1) 33 | 34 | for sp in range(LL0): 35 | np, pp, tot, dt = sp, sp, 0, {} 36 | while np < LS: 37 | t = pos[np] 38 | if t == 0: 39 | tot, dt = 0, {} 40 | pp, np = np + LL0, np + LL0 41 | elif dt.get(t, 0) < dl[t]: 42 | dt[t] = dt.get(t, 0) + 1 43 | tot = tot + 1 44 | if tot == LL: 45 | ans.append(pp) 46 | np = np + LL0 47 | else: 48 | while pos[pp] != t: 49 | tot = tot - 1 50 | dt[pos[pp]] -= 1 51 | pp = pp + LL0 52 | pp = pp + LL0 53 | dt[t] -= 1 54 | tot = tot - 1 55 | return ans 56 | -------------------------------------------------------------------------------- /20120213 Merge k Sorted Lists.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | 6 | ''' 7 | Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 8 | ''' 9 | 10 | # Definition for singly-linked list. 11 | # class ListNode: 12 | # def __init__(self, x): 13 | # self.val = x 14 | # self.next = None 15 | 16 | class Solution: 17 | # @param a list of ListNode 18 | # @return a ListNode 19 | def mergeKLists(self, lists): 20 | self.heap = [[i, lists[i].val] for i in range(len(lists)) if lists[i] != None] 21 | self.hsize = len(self.heap) 22 | for i in range(self.hsize - 1, -1, -1): 23 | self.adjustdown(i) 24 | 25 | nHead = ListNode(0) 26 | head = nHead 27 | while self.hsize > 0: 28 | ind, val = self.heap[0][0], self.heap[0][1] 29 | head.next = lists[ind] 30 | head = head.next 31 | lists[ind] = lists[ind].next 32 | 33 | if lists[ind] is None: 34 | self.heap[0] = self.heap[self.hsize-1] 35 | self.hsize = self.hsize - 1 36 | else: 37 | self.heap[0] = [ind, lists[ind].val] 38 | self.adjustdown(0) 39 | return nHead.next 40 | 41 | def adjustdown(self, p): 42 | lc = lambda x: (x + 1) * 2 - 1 43 | rc = lambda x: (x + 1) * 2 44 | while True: 45 | np, pv = p, self.heap[p][1] 46 | if lc(p) < self.hsize and self.heap[lc(p)][1] < pv: 47 | np, pv = lc(p), self.heap[lc(p)][1] 48 | if rc(p) < self.hsize and self.heap[rc(p)][1] < pv: 49 | np = rc(p) 50 | if np == p: 51 | break 52 | else: 53 | self.heap[np], self.heap[p] = self.heap[p], self.heap[np] 54 | p = np 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /20120215 Reverse Nodes in k-Group.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | ''' 6 | Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 7 | 8 | If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. 9 | 10 | You may not alter the values in the nodes, only nodes itself may be changed. 11 | 12 | Only constant memory is allowed. 13 | 14 | For example, 15 | Given this linked list: 1->2->3->4->5 16 | 17 | For k = 2, you should return: 2->1->4->3->5 18 | 19 | For k = 3, you should return: 3->2->1->4->5 20 | ''' 21 | 22 | # Definition for singly-linked list. 23 | # class ListNode: 24 | # def __init__(self, x): 25 | # self.val = x 26 | # self.next = None 27 | 28 | class Solution: 29 | # @param head, a ListNode 30 | # @param k, an integer 31 | # @return a ListNode 32 | def reverseKGroup(self, head, k): 33 | nHead = ListNode(0) 34 | nHead.next = head 35 | p2, lenl = head, 0 36 | while p2: p2, lenl = p2.next, lenl + 1 37 | now, pre, ind = head, nHead, 1 38 | preHead, preHeadNext = nHead, head 39 | while now: 40 | if lenl - ind < lenl % k: 41 | break 42 | next = now.next 43 | now.next = pre 44 | if ind % k == 0: 45 | preHead.next = now 46 | preHeadNext.next = next 47 | preHead = preHeadNext 48 | pre = preHead 49 | preHeadNext = next 50 | else: 51 | pre = now 52 | now, ind = next, ind + 1 53 | return nHead.next 54 | 55 | 56 | 57 | 58 | a1 = ListNode(1) 59 | a2 = ListNode(2) 60 | a3 = ListNode(3) 61 | a4 = ListNode(4) 62 | a5 = ListNode(5) 63 | a1.next = a2 64 | a2.next = a3 65 | a3.next = a4 66 | a4.next = a5 67 | 68 | 69 | s = Solution() 70 | a1 = s.reverseKGroup(a1, 4) 71 | while a1: 72 | print a1.val 73 | a1 = a1.next 74 | -------------------------------------------------------------------------------- /20120430 Scramble String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | iven a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. 3 | 4 | Below is one possible representation of s1 = "great": 5 | 6 | great 7 | / \ 8 | gr eat 9 | / \ / \ 10 | g r e at 11 | / \ 12 | a t 13 | To scramble the string, we may choose any non-leaf node and swap its two children. 14 | 15 | For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". 16 | 17 | rgeat 18 | / \ 19 | rg eat 20 | / \ / \ 21 | r g e at 22 | / \ 23 | a t 24 | We say that "rgeat" is a scrambled string of "great". 25 | 26 | Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". 27 | 28 | rgtae 29 | / \ 30 | rg tae 31 | / \ / \ 32 | r g ta e 33 | / \ 34 | t a 35 | We say that "rgtae" is a scrambled string of "great". 36 | 37 | Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. 38 | ''' 39 | 40 | class Solution: 41 | # @return a boolean 42 | def isScramble(self, s1, s2): 43 | if len(s1) != len(s2): 44 | return False 45 | if len(s1) == 0: 46 | return True 47 | self.s1, self.s2 = s1, s2 48 | lens = len(s1) 49 | self.dp = [[[-1] * lens for i in range(lens)] * lens for i in range(lens)] 50 | return self.dfs(0, 0, len(s1)) 51 | 52 | def dfs(self, lp, rp, len): 53 | if self.dp[lp][rp][len - 1] >= 0: 54 | return True if self.dp[lp][rp][len - 1] == 1 else False 55 | if len == 1: 56 | return self.s1[lp] == self.s2[rp] 57 | for i in range(1, len): 58 | if self.dfs(lp, rp, i) and self.dfs(lp + i, rp + i, len - i) \ 59 | or self.dfs(lp, rp + i, len - i) and self.dfs(lp + len - i, rp, i): 60 | self.dp[lp][rp][len - 1] = 1 61 | return True 62 | self.dp[lp][rp][len - 1] = 0 63 | return False 64 | 65 | -------------------------------------------------------------------------------- /20131005 Word Break II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. 3 | 4 | Return all such possible sentences. 5 | 6 | For example, given 7 | s = "catsanddog", 8 | dict = ["cat", "cats", "and", "sand", "dog"]. 9 | 10 | A solution is ["cats and dog", "cat sand dog"]. 11 | */ 12 | 13 | class Solution { 14 | public: 15 | vector strRes; 16 | vector seqRes; 17 | vector setVec; 18 | vector wordBreak(string s, unordered_set &dict) { 19 | // IMPORTANT: Please reset any member data you declared, as 20 | // the same Solution instance will be reused for each test case. 21 | 22 | unordered_set::iterator iter; 23 | vector > dp(s.length(), vector(s.length(), -1)); 24 | setVec.clear(); 25 | strRes.clear(); 26 | seqRes.clear(); 27 | for (string ds: dict) { 28 | setVec.push_back(ds); 29 | int pos = 0; 30 | while ((pos = s.find(ds, pos)) != string::npos) 31 | dp[pos][pos+ds.length()-1] = setVec.size(), pos ++; 32 | } 33 | dfs_result(dp, 0, s.length()-1); 34 | return strRes; 35 | } 36 | void dfs_result(vector > &dp, int s, int e) { 37 | if (s > e) { 38 | string s; 39 | for (int i = 0; i < seqRes.size(); i++) { 40 | s.append(setVec[seqRes[i] - 1]); 41 | if (i != seqRes.size() - 1) s.append(" "); 42 | } 43 | strRes.push_back(s); 44 | return; 45 | } 46 | if (dpit(dp, s, e) == 0) return; 47 | for (int i = s; i <= e; i++) { 48 | if (dp[s][i] > 0) { 49 | seqRes.push_back(dp[s][i]); 50 | dfs_result(dp, i + 1, e); 51 | seqRes.pop_back(); 52 | } 53 | } 54 | } 55 | int dpit(vector > &dp, int l, int r) { 56 | if (dp[l][r] != -1) return dp[l][r]; 57 | for (int i = l; i < r; i++) { 58 | if (dpit(dp, l, i) && dpit(dp, i+1, r)) 59 | return dp[l][r] = -2; 60 | } 61 | return dp[l][r] = 0; 62 | } 63 | }; 64 | 65 | -------------------------------------------------------------------------------- /20130924 Clone Graph.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. 3 | 4 | OJ's undirected graph serialization: 5 | 6 | Nodes are labeled uniquely. 7 | We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. 8 | 9 | As an example, consider the serialized graph {0,1,2#1,2#2,2}. 10 | 11 | The graph has a total of three nodes, and therefore contains three parts as separated by #. 12 | 13 | First node is labeled as 0. Connect node 0 to both nodes 1 and 2. 14 | Second node is labeled as 1. Connect node 1 to node 2. 15 | Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. 16 | 17 | Visually, the graph looks like the following: 18 | 19 | 1 20 | / \ 21 | / \ 22 | 0 --- 2 23 | / \ 24 | \_/ 25 | 26 | */ 27 | 28 | /** 29 | * Definition for undirected graph. 30 | * struct UndirectedGraphNode { 31 | * int label; 32 | * vector neighbors; 33 | * UndirectedGraphNode(int x) : label(x) {}; 34 | * }; 35 | */ 36 | #define UNODE UndirectedGraphNode 37 | class Solution { 38 | public: 39 | map::iterator iter; 40 | UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { 41 | // IMPORTANT: Please reset any member data you declared, as 42 | // the same Solution instance will be reused for each test case. 43 | 44 | map nodeMap; 45 | if (node == NULL) return node; 46 | UNODE *nnode = new UNODE(node->label); 47 | nodeMap[node] = nnode; 48 | dfsGraph(nodeMap, node, nnode); 49 | return nnode; 50 | } 51 | void dfsGraph(map &nodeMap, UNODE *node, UNODE *nnode) { 52 | for (int i = 0; i < node->neighbors.size(); i++) { 53 | UNODE *now = node->neighbors[i]; 54 | if ((iter = nodeMap.find(now)) != nodeMap.end()) { 55 | nnode->neighbors.push_back(iter->second); 56 | } else { 57 | UNODE *nnow = new UNODE(now->label); 58 | nodeMap[now] = nnow; 59 | nnode->neighbors.push_back(nnow); 60 | dfsGraph(nodeMap, now, nnow); 61 | } 62 | } 63 | } 64 | }; 65 | -------------------------------------------------------------------------------- /20120403 Text Justification.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. 3 | 4 | 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 has exactly L characters. 5 | 6 | Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. 7 | 8 | For the last line of text, it should be left justified and no extra space is inserted between words. 9 | 10 | For example, 11 | words: ["This", "is", "an", "example", "of", "text", "justification."] 12 | L: 16. 13 | 14 | Return the formatted lines as: 15 | [ 16 | "This is an", 17 | "example of text", 18 | "justification. " 19 | ] 20 | Note: Each word is guaranteed not to exceed L in length. 21 | ''' 22 | class Solution: 23 | # @param words, a list of strings 24 | # @param L, an integer 25 | # @return a list of strings 26 | def fullJustify(self, words, L): 27 | ans, p, plen = [], 0, 0 28 | for i in range(len(words)): 29 | if plen + len(words[i]) + i - p - 1 >= L: 30 | spc = (L - plen) // (i - p - 1) if i - p > 1 else 0 31 | sps = (L - plen - spc * (i - p - 1)) 32 | str = words[p] 33 | for j in range(p + 1, i): 34 | if sps > 0: 35 | str += ' ' 36 | sps -= 1 37 | str += ' ' * spc + words[j] 38 | ans.append(str + ' ' * (L - plen)) 39 | plen, p = 0, i 40 | if i < len(words): 41 | plen += len(words[i]) 42 | str = '' 43 | while p < len(words): 44 | str += words[p] 45 | if len(str) < L: 46 | str += ' ' 47 | p = p + 1 48 | ans.append(str + ' ' * (L - len(str))) 49 | return ans 50 | 51 | s = Solution() 52 | print s.fullJustify(["a","b","c","d","e"], 3) 53 | print s.fullJustify(["Here","is","an","example","of","text","justification."], 14) 54 | print s.fullJustify(["Don't","go","around","saying","the","world","owes","you","a","living;","the","world","owes","you","nothing;","it","was","here","first."], 30) 55 | 56 | -------------------------------------------------------------------------------- /20130210 Word Ladder II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: 3 | 4 | Only one letter can be changed at a time 5 | Each intermediate word must exist in the dictionary 6 | For example, 7 | 8 | Given: 9 | start = "hit" 10 | end = "cog" 11 | dict = ["hot","dot","dog","lot","log"] 12 | Return 13 | [ 14 | ["hit","hot","dot","dog","cog"], 15 | ["hit","hot","lot","log","cog"] 16 | ] 17 | Note: 18 | All words have the same length. 19 | All words contain only lowercase alphabetic characters. 20 | */ 21 | 22 | class Solution { 23 | public: 24 | vector > ans; 25 | vector > findLadders(string start, string end, unordered_set &dict) { 26 | // IMPORTANT: Please reset any member data you declared, as 27 | // the same Solution instance will be reused for each test case. 28 | dict.insert(end); 29 | int dsize = dict.size(), len = start.length(); 30 | unordered_map > next; 31 | unordered_map vis; 32 | queue q; 33 | vector path; 34 | ans.clear(); 35 | q.push(start); 36 | vis[start] = 0; 37 | while (!q.empty()) { 38 | string s = q.front(); q.pop(); 39 | if (s == end) break; 40 | int step = vis[s]; 41 | vector snext; 42 | for (int i = 0; i < len; i++) { 43 | string news = s; 44 | for (char c = 'a'; c <= 'z'; c++) { 45 | news[i] = c; 46 | if (c == s[i] || dict.find(news) == dict.end()) continue; 47 | auto it = vis.find(news); 48 | if (it == vis.end()) { 49 | q.push(news); 50 | vis[news] = step + 1; 51 | } 52 | snext.push_back(news); 53 | } 54 | } 55 | next[s] = snext; 56 | } 57 | path.push_back(start); 58 | dfspath(path, next, vis, start, end); 59 | return ans; 60 | } 61 | void dfspath(vector &path, unordered_map > &next, 62 | unordered_map &vis, string now, string end){ 63 | //cout << now << endl; 64 | if (now == end) ans.push_back(path); 65 | else { 66 | auto vec = next[now]; 67 | int visn = vis[now]; 68 | for (int i = 0; i < vec.size(); i++) { 69 | if (vis[vec[i]] != visn + 1) continue; 70 | path.push_back(vec[i]); 71 | dfspath(path, next, vis, vec[i], end); 72 | path.pop_back(); 73 | } 74 | } 75 | } 76 | }; 77 | --------------------------------------------------------------------------------