├── .gitignore ├── 3Sum Closest.cpp ├── 3Sum.cpp ├── 4Sum.cpp ├── Add Binary.cpp ├── Add Two Numbers.cpp ├── Anagrams.cpp ├── Balanced Binary Tree.cpp ├── Best Time to Buy and Sell Stock II.cpp ├── Best Time to Buy and Sell Stock III.cpp ├── Best Time to Buy and Sell Stock.cpp ├── Binary Tree Inorder Traversal.cpp ├── Binary Tree Level Order Traversal II.cpp ├── Binary Tree Level Order Traversal.cpp ├── Binary Tree Maximum Path Sum.cpp ├── Binary Tree Zigzag Level Order Traversal.cpp ├── Climbing Stairs.cpp ├── Combination Sum II.cpp ├── Combination Sum.cpp ├── Combinations ├── Construct Binary Tree from Inorder and Postorder Traversal.cpp ├── Construct Binary Tree from Preorder and Inorder Traversal.cpp ├── Container With Most Water.cpp ├── Convert Sorted Array to Binary Search Tree.cpp ├── Convert Sorted List to Binary Search Tree.cpp ├── Count and Say.cpp ├── Decode Ways.cpp ├── Distinct Subsequences.cpp ├── Divide Two Integers.cpp ├── Edit Distance.cpp ├── First Missing Positive.cpp ├── Flatten Binary Tree to Linked List.cpp ├── Gas Station.cpp ├── Generate Parentheses.cpp ├── Gray Code.cpp ├── Implement strStr().cpp ├── Insert Interval.cpp ├── Integer to Roman.cpp ├── Interleaving String.cpp ├── Jump Game II.cpp ├── Jump Game.cpp ├── Largest Rectangle in Histogram.cpp ├── Length of Last Word.cpp ├── Letter Combinations of a Phone Number.cpp ├── Longest Common Prefix.cpp ├── Longest Consecutive Sequence.cpp ├── Longest Palindromic Substring.cpp ├── Longest Substring Without Repeating Characters.cpp ├── Longest Valid Parentheses.cpp ├── Maximal Rectangle.cpp ├── Maximum Depth of Binary Tree.cpp ├── Maximum Subarray.cpp ├── Median of Two Sorted Arrays.cpp ├── Merge Intervals.cpp ├── Merge Sorted Array.cpp ├── Merge Two Sorted Lists.cpp ├── Merge k Sorted Lists.cpp ├── Minimum Depth of Binary Tree.cpp ├── Minimum Path Sum.cpp ├── Minimum Window Substring.cpp ├── Multiply Strings.cpp ├── N-Queens II.cpp ├── N-Queens.cpp ├── Next Permutation.cpp ├── Palindrome Number.cpp ├── Palindrome Partitioning II.cpp ├── Palindrome Partitioning.cpp ├── Partition List.cpp ├── Pascal's Triangle II.cpp ├── Pascal's Triangle.cpp ├── Path Sum II.cpp ├── Path Sum.cpp ├── Permutation Sequence.cpp ├── Permutations II.cpp ├── Permutations.cpp ├── Plus One.cpp ├── Populating Next Right Pointers in Each Node II.cpp ├── Populating Next Right Pointers in Each Node.cpp ├── Pow(x, n).cpp ├── README.md ├── Recover Binary Search Tree.cpp ├── Regular Expression Matching.cpp ├── Remove Duplicates from Sorted Array II.cpp ├── Remove Duplicates from Sorted Array.cpp ├── Remove Duplicates from Sorted List II.cpp ├── Remove Duplicates from Sorted List.cpp ├── Remove Element.cpp ├── Remove Nth Node From End of List.cpp ├── Restore IP Addresses.cpp ├── Reverse Integer.cpp ├── Reverse Linked List II.cpp ├── Reverse Nodes in k-Group.cpp ├── Roman to Integer.cpp ├── Rotate Image.cpp ├── Rotate List.cpp ├── Same Tree.cpp ├── Scramble String.cpp ├── Search Insert Position.cpp ├── Search a 2D Matrix.cpp ├── Search for a Range.cpp ├── Search in Rotated Sorted Array II.cpp ├── Search in Rotated Sorted Array.cpp ├── Set Matrix Zeroes.cpp ├── Simplify Path.cpp ├── Single Number II.cpp ├── Single Number.cpp ├── Sort Colors.cpp ├── Spiral Matrix II.cpp ├── Spiral Matrix.cpp ├── Sqrt(x).cpp ├── String to Integer.cpp ├── Subsets II.cpp ├── Subsets.cpp ├── Substring with Concatenation of All Words.cpp ├── Sudoku Solver.cpp ├── Sum Root to Leaf Numbers.cpp ├── Surrounded Regions.cpp ├── Swap Nodes in Pairs.cpp ├── Symmetric Tree.cpp ├── Text Justification.cpp ├── Trapping Rain Water.cpp ├── Triangle.cpp ├── Two Sum.cpp ├── Unique Binary Search Trees II.cpp ├── Unique Binary Search Trees.cpp ├── Unique Paths II.cpp ├── Unique Paths.cpp ├── Valid Number.cpp ├── Valid Palindrome.cpp ├── Valid Parentheses.cpp ├── Valid Sudoku.cpp ├── Validate Binary Search Tree.cpp ├── Wildcard Matching.cpp ├── Word Ladder II.cpp ├── Word Ladder.cpp ├── Word Search.cpp └── ZigZag Conversion.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | 6 | # Compiled Dynamic libraries 7 | *.so 8 | *.dylib 9 | 10 | # Compiled Static libraries 11 | *.lai 12 | *.la 13 | *.a 14 | -------------------------------------------------------------------------------- /3Sum Closest.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int threeSumClosest(vector &num, int target) 5 | { 6 | int closest = 0; 7 | if (num.size() >= 3) 8 | { 9 | sort(num.begin(), num.end()); 10 | closest = num[0] + num[1] + num[2]; 11 | for (size_t i = 0; i + 2 < num.size(); ++i) 12 | { 13 | size_t j = i + 1; 14 | size_t k = num.size() - 1; 15 | while (j < k) 16 | { 17 | int sum = num[i] + num[j] + num[k]; 18 | if (abs(sum - target) < abs(closest - target)) 19 | { 20 | closest = sum; 21 | } 22 | 23 | if (sum < target) 24 | { 25 | ++j; 26 | } 27 | else if (sum > target) 28 | { 29 | --k; 30 | } 31 | else 32 | { 33 | ++j; 34 | --k; 35 | } 36 | } 37 | } 38 | } 39 | 40 | return closest; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /3Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > threeSum(vector &num) 5 | { 6 | vector> result; 7 | if (num.size() >= 3) 8 | { 9 | sort(num.begin(), num.end()); 10 | for (size_t i = 0; i + 2 < num.size(); ++i) 11 | { 12 | size_t j = i + 1; 13 | size_t k = num.size() - 1; 14 | while (j < k) 15 | { 16 | int sum = num[i] + num[j] + num[k]; 17 | if (sum < 0) 18 | { 19 | ++j; 20 | } 21 | else if (sum > 0) 22 | { 23 | --k; 24 | } 25 | else 26 | { 27 | result.push_back(vector({num[i], num[j++], num[k--]})); 28 | } 29 | } 30 | } 31 | } 32 | sort(result.begin(), result.end()); 33 | result.erase(unique(result.begin(), result.end()), result.end()); 34 | return result; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /4Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > fourSum(vector &num, int target) 5 | { 6 | sort(num.begin(), num.end()); 7 | 8 | if (num.size() >= 4) 9 | { 10 | size_t left = 4; 11 | for (size_t right = 4; right < num.size(); ++right) 12 | { 13 | if (num[right] != num[right - 1] || num[right] != num[right - 2] || num[right] != num[right - 3] || num[right] != num[right - 4]) 14 | { 15 | num[left++] = num[right]; 16 | } 17 | } 18 | num.erase(num.begin() + left, num.end()); 19 | } 20 | 21 | vector> result; 22 | vector four(4); 23 | for (size_t c = 2; c < num.size(); ++c) 24 | { 25 | for (size_t d = c + 1; d < num.size(); ++d) 26 | { 27 | int sum2 = num[c] + num[d]; 28 | size_t a = 0, b = c - 1; 29 | while (a < b) 30 | { 31 | int sum4 = sum2 + num[a] + num[b]; 32 | if (sum4 < target) 33 | { 34 | ++a; 35 | } 36 | else if (sum4 > target) 37 | { 38 | --b; 39 | } 40 | else 41 | { 42 | four[0] = num[a]; 43 | four[1] = num[b]; 44 | four[2] = num[c]; 45 | four[3] = num[d]; 46 | result.push_back(four); 47 | ++a; 48 | --b; 49 | } 50 | } 51 | } 52 | } 53 | 54 | sort(result.begin(), result.end()); 55 | result.erase(unique(result.begin(), result.end()), result.end()); 56 | return result; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /Add Binary.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string addBinary(string a, string b) 5 | { 6 | if (a.length() < b.length()) 7 | { 8 | a.swap(b); 9 | } 10 | 11 | size_t diff = a.length() - b.length(); 12 | string c = a; 13 | for (size_t i = 0; i < b.length(); ++i) 14 | { 15 | c[diff + i] += (b[i] - '0'); 16 | } 17 | 18 | for (size_t i = c.length() - 1; i > 0; --i) 19 | { 20 | if (c[i] > '1') 21 | { 22 | c[i] -= 2; 23 | c[i - 1] += 1; 24 | } 25 | } 26 | if (c[0] > '1') 27 | { 28 | c[0] -= 2; 29 | c.insert(c.begin(), '1'); 30 | } 31 | 32 | return c; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Add Two Numbers.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 | { 11 | public: 12 | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 13 | { 14 | ListNode* result = new ListNode(0); 15 | ListNode* l3 = result; 16 | int carry = 0; 17 | while (l1 != NULL && l2 != NULL) 18 | { 19 | int sum = l1->val + l2->val + carry; 20 | l3->next = new ListNode(sum % 10); 21 | carry = sum / 10; 22 | l1 = l1->next; 23 | l2 = l2->next; 24 | l3 = l3->next; 25 | } 26 | 27 | while (l1 != NULL) 28 | { 29 | int sum = l1->val + carry; 30 | l3->next = new ListNode(sum % 10); 31 | carry = sum / 10; 32 | l1 = l1->next; 33 | l3 = l3->next; 34 | } 35 | 36 | while (l2 != NULL) 37 | { 38 | int sum = l2->val + carry; 39 | l3->next = new ListNode(sum % 10); 40 | carry = sum / 10; 41 | l2 = l2->next; 42 | l3 = l3->next; 43 | } 44 | 45 | while (carry != 0) 46 | { 47 | l3->next = new ListNode(carry % 10); 48 | carry /= 10; 49 | l3 = l3->next; 50 | } 51 | 52 | l3 = result; 53 | result = l3->next; 54 | delete l3; 55 | 56 | return result; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /Anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector anagrams(vector &strs) 5 | { 6 | unordered_map> msvs; 7 | for (auto s : strs) 8 | { 9 | string r = s; 10 | sort(r.begin(), r.end()); 11 | msvs[r].push_back(s); 12 | } 13 | 14 | vector result; 15 | for (auto p : msvs) 16 | { 17 | if (p.second.size() > 1) 18 | { 19 | for (auto s : p.second) 20 | { 21 | result.push_back(s); 22 | } 23 | } 24 | } 25 | return result; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Balanced Binary Tree.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 | { 12 | public: 13 | bool isBalanced(TreeNode* root, int& depth) 14 | { 15 | if (root == nullptr) 16 | { 17 | depth = 0; 18 | return true; 19 | } 20 | 21 | int left_depth = 0; 22 | if (!isBalanced(root->left, left_depth)) 23 | { 24 | return false; 25 | } 26 | 27 | int right_depth = 0; 28 | if (!isBalanced(root->right, right_depth)) 29 | { 30 | return false; 31 | } 32 | 33 | depth = max(left_depth, right_depth) + 1; 34 | return (left_depth == right_depth || left_depth == right_depth + 1 || left_depth + 1 == right_depth); 35 | } 36 | 37 | bool isBalanced(TreeNode* root) 38 | { 39 | int depth = 0; 40 | return isBalanced(root, depth); 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector &prices) 4 | { 5 | int profit = 0; 6 | size_t i = 0; 7 | while (i < prices.size()) 8 | { 9 | while (i + 1 < prices.size() && prices[i + 1] <= prices[i]) 10 | { 11 | i += 1; 12 | } 13 | int buy = prices[i]; 14 | i += 1; 15 | 16 | if (i >= prices.size()) 17 | { 18 | break; 19 | } 20 | 21 | while (i + 1 < prices.size() && prices[i + 1] >= prices[i]) 22 | { 23 | i += 1; 24 | } 25 | int cell = prices[i]; 26 | i += 1; 27 | 28 | profit += (cell - buy); 29 | } 30 | 31 | return profit; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock III.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxProfit(vector &prices) 5 | { 6 | int max_profit = 0; 7 | 8 | vector profit_left(prices.size(), 0); 9 | if (!prices.empty()) 10 | { 11 | int buy = prices.front(); 12 | for (size_t i = 1; i < prices.size(); ++i) 13 | { 14 | int profit = prices[i] - buy; 15 | profit_left[i] = max(profit_left[i-1], profit); 16 | buy = min(buy, prices[i]); 17 | } 18 | } 19 | 20 | vector profit_right(prices.size(), 0); 21 | if (!prices.empty()) 22 | { 23 | int cell = prices.back(); 24 | for (int i = prices.size() - 2; i >= 0; --i) 25 | { 26 | int profit = cell - prices[i]; 27 | profit_right[i] = max(profit_right[i+1], profit); 28 | cell = max(cell, prices[i]); 29 | } 30 | } 31 | 32 | if (!prices.empty()) 33 | { 34 | max_profit = profit_left.back(); 35 | } 36 | 37 | for (size_t i = 1; i < prices.size(); ++i) 38 | { 39 | int sum = profit_left[i-1] + profit_right[i]; 40 | max_profit = max(max_profit, sum); 41 | } 42 | 43 | return max_profit; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxProfit(vector &prices) 5 | { 6 | int profit = 0; 7 | 8 | if (!prices.empty()) 9 | { 10 | int buy = prices[0]; 11 | for (size_t i = 1; i < prices.size(); ++i) 12 | { 13 | if (prices[i] - buy > profit) 14 | { 15 | profit = prices[i] - buy; 16 | } 17 | if (prices[i] < buy) 18 | { 19 | buy = prices[i]; 20 | } 21 | } 22 | } 23 | 24 | return profit; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Binary Tree Inorder 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 | { 12 | public: 13 | vector inorderTraversal(TreeNode *root) 14 | { 15 | vector result; 16 | stack s; 17 | TreeNode* cur = root; 18 | while (true) 19 | { 20 | if (NULL != cur) 21 | { 22 | s.push(cur); 23 | cur = cur->left; 24 | } 25 | else if (!s.empty()) 26 | { 27 | result.push_back(s.top()->val); 28 | cur = s.top()->right; 29 | s.pop(); 30 | } 31 | else 32 | { 33 | break; 34 | } 35 | } 36 | return result; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Binary Tree Level Order Traversal II.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 | { 12 | public: 13 | vector > levelOrderBottom(TreeNode *root) 14 | { 15 | vector> all_values; 16 | vector level_nodes; 17 | if (root != NULL) 18 | { 19 | level_nodes.push_back(root); 20 | while (!level_nodes.empty()) 21 | { 22 | vector level_values; 23 | for (auto it = level_nodes.begin(); it != level_nodes.end(); ++it) 24 | { 25 | level_values.push_back((*it)->val); 26 | } 27 | all_values.push_back(level_values); 28 | 29 | vector nodes; 30 | level_nodes.swap(nodes); 31 | for (auto it = nodes.begin(); it != nodes.end(); ++it) 32 | { 33 | if ((*it)->left != NULL) 34 | { 35 | level_nodes.push_back((*it)->left); 36 | } 37 | if ((*it)->right != NULL) 38 | { 39 | level_nodes.push_back((*it)->right); 40 | } 41 | } 42 | } 43 | } 44 | reverse(all_values.begin(), all_values.end()); 45 | return all_values; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Binary Tree Level Order 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 | { 12 | public: 13 | vector > levelOrder(TreeNode *root) 14 | { 15 | vector> all_values; 16 | vector level_nodes; 17 | if (root != NULL) 18 | { 19 | level_nodes.push_back(root); 20 | while (!level_nodes.empty()) 21 | { 22 | vector level_values; 23 | for (auto it = level_nodes.begin(); it != level_nodes.end(); ++it) 24 | { 25 | level_values.push_back((*it)->val); 26 | } 27 | all_values.push_back(level_values); 28 | 29 | vector nodes; 30 | level_nodes.swap(nodes); 31 | for (auto it = nodes.begin(); it != nodes.end(); ++it) 32 | { 33 | if ((*it)->left != NULL) 34 | { 35 | level_nodes.push_back((*it)->left); 36 | } 37 | if ((*it)->right != NULL) 38 | { 39 | level_nodes.push_back((*it)->right); 40 | } 41 | } 42 | } 43 | } 44 | return all_values; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Binary Tree Maximum Path Sum.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 | { 12 | public: 13 | int maxSidePathSum(TreeNode *root, int& max_path_sum) 14 | { 15 | int max_root_sum = root->val; 16 | 17 | int left_sum = 0; 18 | if (root->left != NULL) 19 | { 20 | left_sum = maxSidePathSum(root->left, max_path_sum); 21 | if (left_sum > 0) 22 | { 23 | max_root_sum += left_sum; 24 | } 25 | } 26 | 27 | int right_sum = 0; 28 | if (root->right != NULL) 29 | { 30 | right_sum = maxSidePathSum(root->right, max_path_sum); 31 | if (right_sum > 0) 32 | { 33 | max_root_sum += right_sum; 34 | } 35 | } 36 | 37 | max_path_sum = max(max_path_sum, max_root_sum); 38 | 39 | return root->val + max(max(left_sum, right_sum), 0); 40 | } 41 | 42 | int maxPathSum(TreeNode *root) 43 | { 44 | int max_path_sum = root->val; 45 | maxSidePathSum(root, max_path_sum); 46 | return max_path_sum; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Binary Tree Zigzag Level Order 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 | { 12 | public: 13 | vector > zigzagLevelOrder(TreeNode *root) 14 | { 15 | vector> all_values; 16 | vector level_nodes; 17 | if (root != NULL) 18 | { 19 | level_nodes.push_back(root); 20 | while (!level_nodes.empty()) 21 | { 22 | vector level_values; 23 | for (auto it = level_nodes.begin(); it != level_nodes.end(); ++it) 24 | { 25 | level_values.push_back((*it)->val); 26 | } 27 | all_values.push_back(level_values); 28 | 29 | vector nodes; 30 | level_nodes.swap(nodes); 31 | for (auto it = nodes.begin(); it != nodes.end(); ++it) 32 | { 33 | if ((*it)->left != NULL) 34 | { 35 | level_nodes.push_back((*it)->left); 36 | } 37 | if ((*it)->right != NULL) 38 | { 39 | level_nodes.push_back((*it)->right); 40 | } 41 | } 42 | } 43 | } 44 | for (size_t i = 1; i < all_values.size(); i += 2) 45 | { 46 | reverse(all_values[i].begin(), all_values[i].end()); 47 | } 48 | return all_values; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int climbStairs(int n) 5 | { 6 | int a = 0; 7 | int b = 0; 8 | int c = 1; 9 | for (int i = 0; i < n; ++i) 10 | { 11 | a = b; 12 | b = c; 13 | c = a + b; 14 | } 15 | return c; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Combination Sum II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> combinationSum2(vector& num, int target) 5 | { 6 | sort(num.begin(), num.end()); 7 | 8 | set> result_set; 9 | vector> combination({{}}); 10 | for (int n : num) 11 | { 12 | size_t count = combination.size(); 13 | for (size_t i = 0; i < count; ++i) 14 | { 15 | int sum = accumulate(combination[i].begin(), combination[i].end(), 0); 16 | if (sum + n < target) 17 | { 18 | combination.push_back(combination[i]); 19 | combination.back().push_back(n); 20 | } 21 | else if (sum + n == target) 22 | { 23 | auto x = combination[i]; 24 | x.push_back(n); 25 | result_set.insert(x); 26 | } 27 | } 28 | } 29 | 30 | vector> result; 31 | for (auto& x : result_set) 32 | { 33 | result.push_back(x); 34 | } 35 | 36 | return result; 37 | } 38 | }; 39 | 40 | //============================================================ 41 | 42 | class Solution2 43 | { 44 | public: 45 | vector> combinationSum2(vector& num, int target) 46 | { 47 | sort(num.begin(), num.end()); 48 | 49 | vector> result; 50 | vector> combination({{}}); 51 | for (int n : num) 52 | { 53 | size_t count = combination.size(); 54 | for (size_t i = 0; i < count; ++i) 55 | { 56 | int sum = accumulate(combination[i].begin(), combination[i].end(), 0); 57 | if (sum + n < target) 58 | { 59 | combination.push_back(combination[i]); 60 | combination.back().push_back(n); 61 | } 62 | else if (sum + n == target) 63 | { 64 | result.push_back(combination[i]); 65 | result.back().push_back(n); 66 | } 67 | } 68 | } 69 | 70 | sort(result.begin(), result.end()); 71 | result.erase(unique(result.begin(), result.end()), result.end()); 72 | 73 | return result; 74 | } 75 | }; 76 | -------------------------------------------------------------------------------- /Combination Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > combinationSum(vector &candidates, int target) 5 | { 6 | sort(candidates.begin(), candidates.end(), greater()); 7 | 8 | vector> result; 9 | vector> combination({{}}); 10 | for (int n : candidates) 11 | { 12 | vector> temp; 13 | combination.swap(temp); 14 | 15 | for (auto x : temp) 16 | { 17 | int sum = accumulate(x.begin(), x.end(), 0); 18 | for (; sum < target; sum += n) 19 | { 20 | combination.push_back(x); 21 | x.push_back(n); 22 | } 23 | 24 | if (sum == target) 25 | { 26 | result.push_back(x); 27 | } 28 | } 29 | } 30 | 31 | for (auto& x : result) 32 | { 33 | sort(x.begin(), x.end()); 34 | } 35 | 36 | return result; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Combinations: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> combine(int n, int k) 5 | { 6 | vector one; 7 | for (int i = n - k + 1; i <= n; ++i) 8 | { 9 | one.push_back(i); 10 | } 11 | 12 | vector> all({one}); 13 | while (true) 14 | { 15 | int i = k - 1; 16 | for (; i > 0; --i) 17 | { 18 | if (one[i] > one[i-1] + 1) 19 | { 20 | break; 21 | } 22 | } 23 | 24 | if (i > 0 || one[i] > 1) 25 | { 26 | one[i] -= 1; 27 | for (int j = k - 1; j > i; --j) 28 | { 29 | one[j] = n + 1 - k + j; 30 | } 31 | } 32 | else 33 | { 34 | break; 35 | } 36 | 37 | all.push_back(one); 38 | } 39 | 40 | return all; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Construct Binary Tree from Inorder and 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 | { 12 | public: 13 | TreeNode* buildTree(vector::iterator inbegin, vector::iterator inend, vector::iterator postbegin, vector::iterator postend) 14 | { 15 | TreeNode* root = nullptr; 16 | if (postbegin != postend) 17 | { 18 | root = new TreeNode(*(postend - 1)); 19 | auto it = find(inbegin, inend, *(postend - 1)); 20 | root->left = buildTree(inbegin, it, postbegin, postbegin + (it - inbegin)); 21 | root->right = buildTree(it + 1, inend, postbegin + (it - inbegin), postend - 1); 22 | } 23 | return root; 24 | } 25 | 26 | TreeNode* buildTree(vector& inorder, vector& postorder) 27 | { 28 | return buildTree(inorder.begin(), inorder.end(), postorder.begin(), postorder.end()); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Construct Binary Tree from Preorder and Inorder 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 | { 12 | public: 13 | TreeNode* buildTree(vector::iterator prebegin, vector::iterator preend, vector::iterator inbegin, vector::iterator inend) 14 | { 15 | TreeNode* root = nullptr; 16 | if (prebegin != preend) 17 | { 18 | root = new TreeNode(*prebegin); 19 | auto it = find(inbegin, inend, *prebegin); 20 | root->left = buildTree(prebegin + 1, prebegin + 1 + (it - inbegin), inbegin, it); 21 | root->right = buildTree(prebegin + 1 + (it - inbegin), preend, it + 1, inend); 22 | } 23 | return root; 24 | } 25 | 26 | TreeNode* buildTree(vector& preorder, vector& inorder) 27 | { 28 | return buildTree(preorder.begin(), preorder.end(), inorder.begin(), inorder.end()); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Container With Most Water.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxArea(vector &height) 5 | { 6 | vector> height2position(height.size()); 7 | for (int i = 0; i < height.size(); ++i) 8 | { 9 | height2position.push_back(make_pair(height[i], i)); 10 | } 11 | sort(height2position.begin(), height2position.end(), greater>()); 12 | int max_area = 0; 13 | int min_position = height2position[0].second; 14 | int max_position = height2position[0].second; 15 | for (int i = 1; i < height2position.size(); ++i) 16 | { 17 | min_position = min(min_position, height2position[i].second); 18 | max_position = max(max_position, height2position[i].second); 19 | int area = (max_position - min_position) * height2position[i].first; 20 | max_area = max(max_area, area); 21 | } 22 | return max_area; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Convert Sorted Array to Binary Search Tree.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 | { 12 | public: 13 | TreeNode* sortedArrayToBST(const vector& num, size_t begin, size_t end) 14 | { 15 | if (begin == end) 16 | { 17 | return nullptr; 18 | } 19 | 20 | size_t middle = (begin + end) / 2; 21 | TreeNode* root = new TreeNode(num[middle]); 22 | root->left = sortedArrayToBST(num, begin, middle); 23 | root->right = sortedArrayToBST(num, middle + 1, end); 24 | return root; 25 | } 26 | 27 | TreeNode* sortedArrayToBST(vector& num) 28 | { 29 | return sortedArrayToBST(num, 0, num.size()); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Convert Sorted List to Binary Search Tree.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 | /** 10 | * Definition for binary tree 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 | * }; 17 | */ 18 | class Solution 19 | { 20 | public: 21 | TreeNode* sortedArrayToBST(const vector& num, size_t begin, size_t end) 22 | { 23 | if (begin == end) 24 | { 25 | return nullptr; 26 | } 27 | 28 | size_t middle = (begin + end) / 2; 29 | TreeNode* root = new TreeNode(num[middle]); 30 | root->left = sortedArrayToBST(num, begin, middle); 31 | root->right = sortedArrayToBST(num, middle + 1, end); 32 | return root; 33 | } 34 | 35 | TreeNode *sortedListToBST(ListNode *head) 36 | { 37 | vector num; 38 | while (head != nullptr) 39 | { 40 | num.push_back(head->val); 41 | head = head->next; 42 | } 43 | return sortedArrayToBST(num, 0, num.size()); 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Count and Say.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string countAndSay(int n) 5 | { 6 | string s = "1"; 7 | string b; 8 | for (int i = 1; i < n; ++i) 9 | { 10 | for (size_t i = 0; i < s.length(); ) 11 | { 12 | size_t j = i + 1; 13 | while (j < s.length() && s[j] == s[i]) 14 | { 15 | ++j; 16 | } 17 | b.append(1, static_cast('0' + (j - i))); 18 | b.append(1, s[i]); 19 | i = j; 20 | } 21 | s.swap(b); 22 | b.clear(); 23 | } 24 | return s; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Decode Ways.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int numDecodings(string s) 5 | { 6 | if (s.empty()) 7 | { 8 | return 0; 9 | } 10 | 11 | if (s[0] == '0') 12 | { 13 | return 0; 14 | } 15 | 16 | int a = 1; 17 | int b = 1; 18 | 19 | for (size_t i = 1; i < s.length(); ++i) 20 | { 21 | int c = 0; 22 | 23 | int two_digit_value = (s[i-1] - '0') * 10 + (s[i] - '0'); 24 | if (two_digit_value >= 10 && two_digit_value <= 26) 25 | { 26 | c += a; 27 | } 28 | 29 | if (s[i] > '0') 30 | { 31 | c += b; 32 | } 33 | 34 | a = b; 35 | b = c; 36 | 37 | if (b == 0) 38 | { 39 | break; 40 | } 41 | } 42 | 43 | return b; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Distinct Subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int numDistinct(string S, string T) 5 | { 6 | int num = 0; 7 | if (S.length() >= T.length() && !T.empty()) 8 | { 9 | vector d(S.length(), 0); 10 | if (S[0] == T[0]) 11 | { 12 | d[0] = 1; 13 | } 14 | for (size_t i = 1; i < S.length(); ++i) 15 | { 16 | if (S[i] == T[0]) 17 | { 18 | d[i] = d[i-1] + 1; 19 | } 20 | else 21 | { 22 | d[i] = d[i-1]; 23 | } 24 | } 25 | 26 | for (size_t k = 1; k < T.length(); ++k) 27 | { 28 | vector temp(S.length(), 0); 29 | d.swap(temp); 30 | 31 | for (size_t i = k; i + (T.length() - 1 - k) < S.length(); ++i) 32 | { 33 | if (S[i] == T[k]) 34 | { 35 | d[i] = d[i-1] + temp[i-1]; 36 | } 37 | else 38 | { 39 | d[i] = d[i-1]; 40 | } 41 | } 42 | } 43 | num = d.back(); 44 | } 45 | 46 | return num; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Divide Two Integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int divide(int dividend, int divisor) 5 | { 6 | long long llDividend = dividend; 7 | long long llDivisor = divisor; 8 | int negative = false; 9 | if (llDividend < 0) 10 | { 11 | negative = !negative; 12 | llDividend = -llDividend; 13 | } 14 | if (llDivisor < 0) 15 | { 16 | negative = !negative; 17 | llDivisor = -llDivisor; 18 | } 19 | 20 | long long quotient = 0; 21 | while (llDividend >= llDivisor) 22 | { 23 | int n = 1; 24 | while ((llDividend >> n) >= llDivisor) 25 | { 26 | n += 1; 27 | } 28 | quotient += (1 << (n - 1)); 29 | llDividend = llDividend - (llDivisor << (n - 1)); 30 | } 31 | 32 | if (negative) 33 | { 34 | quotient = -quotient; 35 | } 36 | return quotient; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Edit Distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minDistance(string word1, string word2) 5 | { 6 | if (word1.empty()) 7 | { 8 | return word2.length(); 9 | } 10 | else if (word2.empty()) 11 | { 12 | return word1.length(); 13 | } 14 | 15 | vector dist(word1.length() + 1); 16 | for (int i1 = 1; i1 <= word1.length(); ++i1) 17 | { 18 | dist[i1] = i1; 19 | } 20 | 21 | for (int i2 = 1; i2 <= word2.length(); ++i2) 22 | { 23 | int distLeftUp = dist[0]; 24 | dist[0] = i2; 25 | for (int i1 = 1; i1 <= word1.length(); ++i1) 26 | { 27 | int distLeftUpBack = distLeftUp; 28 | distLeftUp = dist[i1]; 29 | if (word2[i2-1] == word1[i1-1]) 30 | { 31 | dist[i1] = distLeftUpBack; 32 | } 33 | else 34 | { 35 | // distLeft -> dist[i1] 36 | // distUp -> dist[i1+1] 37 | dist[i1] = min(min(dist[i1-1], dist[i1]), distLeftUpBack) + 1; 38 | } 39 | } 40 | } 41 | return dist.back(); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /First Missing Positive.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int firstMissingPositive(int A[], int n) 5 | { 6 | if (n == 0) 7 | { 8 | return 1; 9 | } 10 | 11 | for (int i = 0; i < n; ++i) 12 | { 13 | while (A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i]) 14 | { 15 | int x = A[i]; 16 | A[i] = A[x - 1]; 17 | A[x - 1] = x; 18 | } 19 | } 20 | 21 | int m = 1; 22 | while (m <= n && A[m-1] == m) 23 | { 24 | ++m; 25 | } 26 | return m; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Flatten Binary Tree to Linked List.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 | { 12 | public: 13 | void flatten(TreeNode *root) 14 | { 15 | TreeNode* cur = root; 16 | while (NULL != cur) 17 | { 18 | if (NULL != cur->left) 19 | { 20 | TreeNode* end = cur->left; 21 | while (true) 22 | { 23 | if (NULL != end->right) 24 | { 25 | end = end->right; 26 | } 27 | else if (NULL != end->left) 28 | { 29 | end = end->left; 30 | } 31 | else 32 | { 33 | break; 34 | } 35 | } 36 | end->right = cur->right; 37 | cur->right = cur->left; 38 | cur->left = NULL; 39 | } 40 | 41 | cur = cur->right; 42 | } 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Gas Station.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int canCompleteCircuit(vector &gas, vector &cost) 5 | { 6 | int total(gas[0]-cost[0]), mt(total), mi(0); 7 | for (int i = 1; i < gas.size(); ++i) 8 | { 9 | total += (gas[i] - cost[i]); 10 | if (total < mt) 11 | { 12 | mt = total; 13 | mi = i; 14 | } 15 | } 16 | 17 | return total >= 0 ? (mi + 1) % (gas.size()) : -1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Generate Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector generateParenthesis(int n) 5 | { 6 | vector> parenthesis(n + 1); 7 | parenthesis[0].push_back(""); 8 | for (int i = 1; i <= n; ++i) 9 | { 10 | for (int left = 0; left < i; ++left) 11 | { 12 | int right = i - 1 - left; 13 | for (auto sl : parenthesis[left]) 14 | { 15 | for (auto sr : parenthesis[right]) 16 | { 17 | parenthesis[i].push_back("(" + sl + ")" + sr); 18 | } 19 | } 20 | } 21 | } 22 | return parenthesis[n]; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Gray Code.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector grayCode(int n) 5 | { 6 | vector gray({0}); 7 | int power = 1; 8 | for (int i = 0; i < n; ++i) 9 | { 10 | for (int i = 0; i < power; ++i) 11 | { 12 | gray.push_back(gray[i] + power); 13 | } 14 | reverse(gray.begin() + power, gray.begin() + power * 2); 15 | power *= 2; 16 | } 17 | return gray; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Implement strStr().cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | char *strStr(char *haystack, char *needle) 5 | { 6 | if (*needle == 0) 7 | { 8 | return haystack; 9 | } 10 | 11 | int hlen = strlen(haystack); 12 | int nlen = strlen(needle); 13 | 14 | vector next(nlen + 1); 15 | next[1] = next[0] = 0; 16 | int k = 0; 17 | for (int i = 2; i <= nlen; ++i) 18 | { 19 | for (; k != 0 && needle[k] != needle[i-1]; k = next[k]) 20 | nullptr; 21 | if (needle[k] == needle[i-1]) 22 | k++; 23 | next[i] = k; 24 | } 25 | 26 | int hi = 0, ni = 0; 27 | while (hi < hlen) 28 | { 29 | for (ni = next[ni]; ni < nlen && needle[ni] == haystack[hi]; ni++, hi++) 30 | nullptr; 31 | if (ni == 0) 32 | hi++; 33 | else if (ni == nlen) 34 | { 35 | return haystack + hi - nlen; 36 | } 37 | } 38 | 39 | return nullptr; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Insert Interval.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | static bool cmp(const Interval& left, const Interval& right) 14 | { 15 | return (left.start < right.start); 16 | } 17 | 18 | vector insert(vector &intervals, Interval newInterval) 19 | { 20 | vector result(intervals); 21 | result.push_back(newInterval); 22 | if (!result.empty()) 23 | { 24 | sort(result.begin(), result.end(), cmp); 25 | auto it1 = result.begin(); 26 | auto it2 = it1 + 1; 27 | for (; it2 != result.end(); ++it2) 28 | { 29 | if (it2->start <= it1->end) 30 | { 31 | it1->end = max(it1->end, it2->end); 32 | } 33 | else 34 | { 35 | ++it1; 36 | *it1 = *it2; 37 | } 38 | } 39 | ++it1; 40 | result.erase(it1, result.end()); 41 | } 42 | return result; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Integer to Roman.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string intToRoman(int num) 5 | { 6 | const string one[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 7 | const string ten[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 8 | const string hundred[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 9 | const string thousand[] = {"", "M", "MM", "MMM"}; 10 | return thousand[num/1000] + hundred[num%1000/100] + ten[num%100/10] + one[num%10]; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Interleaving String.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isInterleave(string s1, string s2, string s3) 5 | { 6 | if (s1.size() + s2.size() != s3.size()) 7 | { 8 | return false; 9 | } 10 | 11 | vector match(s1.size() + 1, false); 12 | match[0] = true; 13 | 14 | for (size_t c3 = 1; c3 <= s2.size(); ++c3) 15 | { 16 | for (size_t c1 = min(s1.size(), c3); c1 >= 1; --c1) 17 | { 18 | match[c1] = (match[c1-1] && s1[c1-1] == s3[c3-1] || match[c1] && c1 < c3 && s2[c3-c1-1] == s3[c3-1]); 19 | } 20 | match[0] = (match[0] && s2[c3-1] == s3[c3-1]); 21 | } 22 | 23 | for (size_t c3 = s2.size() + 1; c3 <= s3.size(); ++c3) 24 | { 25 | for (size_t c1 = min(s1.size(), c3); c1 >= c3 - s2.size() ; --c1) 26 | { 27 | match[c1] = match[c1-1] && s1[c1-1] == s3[c3-1] || match[c1] && c1 < c3 && s2[c3-c1-1] == s3[c3-1]; 28 | } 29 | } 30 | 31 | return match[s1.size()]; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Jump Game II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int jump(int A[], int n) 5 | { 6 | int step = 0; 7 | int from = 0; 8 | int max_jump = 0; 9 | while (max_jump < n - 1) 10 | { 11 | ++step; 12 | int new_max_jump = max_jump; 13 | while (from <= max_jump) 14 | { 15 | int to = from + A[from]; 16 | if (to > new_max_jump) 17 | { 18 | new_max_jump = to; 19 | } 20 | ++from; 21 | } 22 | max_jump = new_max_jump; 23 | } 24 | 25 | return step; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Jump Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool canJump(int A[], int n) 5 | { 6 | if (n == 1) 7 | { 8 | return true; 9 | } 10 | 11 | for (int i = n - 2; i >= 0; --i) 12 | { 13 | if (A[i] == 0) 14 | { 15 | int p = i; 16 | for (--i; i >= 0; --i) 17 | { 18 | if (A[i] + i > p) 19 | { 20 | break; 21 | } 22 | } 23 | if (i < 0) 24 | { 25 | return false; 26 | } 27 | } 28 | } 29 | return true; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Largest Rectangle in Histogram.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector calc_width_before(const vector& height) 5 | { 6 | vector width; 7 | if (!height.empty()) 8 | { 9 | width.push_back(1); 10 | vector > height_width({{height[0], 1}}); 11 | for (size_t i = 1; i < height.size(); ++i) 12 | { 13 | if (height[i] > height[i - 1]) 14 | { 15 | height_width.push_back(make_pair(height[i], 1)); 16 | width.push_back(1); 17 | } 18 | else 19 | { 20 | int w = 1; 21 | while (!height_width.empty() && height_width.back().first >= height[i]) 22 | { 23 | w += height_width.back().second; 24 | height_width.pop_back(); 25 | } 26 | height_width.push_back(make_pair(height[i], w)); 27 | width.push_back(w); 28 | } 29 | } 30 | } 31 | return width; 32 | } 33 | 34 | int largestRectangleArea(vector &height) 35 | { 36 | int largest = 0; 37 | 38 | vector left_width = calc_width_before(height); 39 | 40 | reverse(height.begin(), height.end()); 41 | vector right_width = calc_width_before(height); 42 | reverse(right_width.begin(), right_width.end()); 43 | reverse(height.begin(), height.end()); 44 | 45 | for (int i = 0; i < height.size(); ++i) 46 | { 47 | int area = (left_width[i] + right_width[i] - 1) * height[i]; 48 | if (area > largest) 49 | { 50 | largest = area; 51 | } 52 | } 53 | 54 | return largest; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Length of Last Word.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int lengthOfLastWord(const char *s) 5 | { 6 | int length = 0; 7 | int last_length = 0; 8 | while (true) 9 | { 10 | if (isalpha(*s)) 11 | { 12 | ++length; 13 | } 14 | else 15 | { 16 | if (length != 0) 17 | { 18 | last_length = length; 19 | length = 0; 20 | } 21 | 22 | if (*s == '\0') 23 | { 24 | break; 25 | } 26 | } 27 | 28 | ++s; 29 | } 30 | 31 | return last_length; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Letter Combinations of a Phone Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector letterCombinations(string digits) 5 | { 6 | vector result({""}), temp; 7 | vector digit2letters({" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}); 8 | for (auto it = digits.begin(); it != digits.end(); ++it) 9 | { 10 | int digit = (*it - '0'); 11 | string letters = digit2letters[digit]; 12 | 13 | result.swap(temp); 14 | result.clear(); 15 | for (size_t i = 0; i < temp.size(); ++i) 16 | { 17 | for (size_t j = 0; j < letters.size(); ++j) 18 | { 19 | result.push_back(temp[i]); 20 | result.back().push_back(letters[j]); 21 | } 22 | } 23 | } 24 | return result; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Longest Common Prefix.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string longestCommonPrefix(vector& strs) 5 | { 6 | if (strs.empty()) 7 | { 8 | return string(""); 9 | } 10 | 11 | size_t longest = strs[0].length(); 12 | for (size_t i = 1; i < strs.size(); ++i) 13 | { 14 | if (strs[i].length() < longest) 15 | { 16 | longest = strs[i].length(); 17 | } 18 | 19 | for (size_t j = 0; j < longest; ++j) 20 | { 21 | if (strs[0][j] != strs[i][j]) 22 | { 23 | longest = j; 24 | break; 25 | } 26 | } 27 | } 28 | 29 | return strs[0].substr(0, longest); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Longest Consecutive Sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int longestConsecutive(vector &num) 5 | { 6 | unordered_set us; 7 | for (auto x : num) 8 | { 9 | us.insert(x); 10 | } 11 | 12 | int longest = 0; 13 | for (auto x: num) 14 | { 15 | auto it = us.find(x); 16 | if (it != us.end()) 17 | { 18 | us.erase(it); 19 | 20 | int small = x - 1; 21 | while (true) 22 | { 23 | it = us.find(small); 24 | if (it == us.end()) 25 | { 26 | break; 27 | } 28 | us.erase(it); 29 | small -= 1; 30 | } 31 | 32 | int big = x + 1; 33 | while (true) 34 | { 35 | it = us.find(big); 36 | if (it == us.end()) 37 | { 38 | break; 39 | } 40 | us.erase(it); 41 | big += 1; 42 | } 43 | 44 | int length = big - small - 1; 45 | if (length > longest) 46 | { 47 | longest = length; 48 | } 49 | } 50 | } 51 | return longest; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /Longest Palindromic Substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string longestPalindrome(string s) 5 | { 6 | size_t slen = s.length(); 7 | 8 | string result; 9 | size_t maxlen = 0; 10 | 11 | for (size_t sum = 0; sum <= (slen - 1) * 2; ++sum) 12 | { 13 | size_t count = 0; 14 | size_t i = (sum + 1) / 2; 15 | for (; i <= min(slen - 1, sum); ++i) 16 | { 17 | if (s[i] != s[sum - i]) 18 | { 19 | break; 20 | } 21 | ++count; 22 | } 23 | 24 | size_t len = count * 2 - ((sum + 1) % 2); 25 | if (len > maxlen) 26 | { 27 | result = s.substr((sum + 1 - len) / 2, len); 28 | maxlen = len; 29 | } 30 | } 31 | 32 | return result; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Longest Substring Without Repeating Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int lengthOfLongestSubstring(string s) 5 | { 6 | int position[128]; 7 | fill(position, position + sizeof(position) / sizeof(position[0]), -1); 8 | int start = -1; 9 | 10 | int result = 0; 11 | for (int i = 0; i < s.length(); ++i) 12 | { 13 | start = max(start, position[s[i]]); 14 | int len = i - start; 15 | result = max(result, len); 16 | position[s[i]] = i; 17 | } 18 | 19 | return result; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Longest Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int longestValidParentheses(string s) 5 | { 6 | int longest = 0; 7 | vector position_count; 8 | 9 | int left = 0; 10 | int count = 0; 11 | for (size_t i = 0; i < s.length(); ++i) 12 | { 13 | if (s[i] == '(') 14 | { 15 | ++left; 16 | position_count.push_back(count); 17 | count = 0; 18 | } 19 | else 20 | { 21 | if (left != 0) 22 | { 23 | --left; 24 | count += (1 + position_count.back()); 25 | if (count > longest) 26 | { 27 | longest = count; 28 | } 29 | position_count.pop_back(); 30 | } 31 | else 32 | { 33 | count = 0; 34 | } 35 | } 36 | } 37 | 38 | return longest * 2; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Maximal Rectangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector calc_width_before(const vector& height) 5 | { 6 | vector width; 7 | if (!height.empty()) 8 | { 9 | width.push_back(1); 10 | vector > height_width({{height[0], 1}}); 11 | for (size_t i = 1; i < height.size(); ++i) 12 | { 13 | if (height[i] > height[i - 1]) 14 | { 15 | height_width.push_back(make_pair(height[i], 1)); 16 | width.push_back(1); 17 | } 18 | else 19 | { 20 | int w = 1; 21 | while (!height_width.empty() && height_width.back().first >= height[i]) 22 | { 23 | w += height_width.back().second; 24 | height_width.pop_back(); 25 | } 26 | height_width.push_back(make_pair(height[i], w)); 27 | width.push_back(w); 28 | } 29 | } 30 | } 31 | return width; 32 | } 33 | 34 | int largestRectangleArea(vector& height) 35 | { 36 | int largest = 0; 37 | 38 | vector left_width = calc_width_before(height); 39 | 40 | reverse(height.begin(), height.end()); 41 | vector right_width = calc_width_before(height); 42 | reverse(right_width.begin(), right_width.end()); 43 | reverse(height.begin(), height.end()); 44 | 45 | for (int i = 0; i < height.size(); ++i) 46 | { 47 | int area = (left_width[i] + right_width[i] - 1) * height[i]; 48 | if (area > largest) 49 | { 50 | largest = area; 51 | } 52 | } 53 | 54 | return largest; 55 | } 56 | 57 | int maximalRectangle(vector>& matrix) 58 | { 59 | int largest = 0; 60 | if (!matrix.empty()) 61 | { 62 | size_t rows = matrix.size(); 63 | size_t columns = matrix[0].size(); 64 | vector height(columns, 0); 65 | for (size_t r = 0; r < rows; ++r) 66 | { 67 | for (size_t c = 0; c < columns; ++c) 68 | { 69 | if (matrix[r][c] == '1') 70 | { 71 | height[c] += 1; 72 | } 73 | else 74 | { 75 | height[c] = 0; 76 | } 77 | } 78 | int temp_largest = largestRectangleArea(height); 79 | if (temp_largest > largest) 80 | { 81 | largest = temp_largest; 82 | } 83 | } 84 | } 85 | 86 | return largest; 87 | } 88 | }; 89 | -------------------------------------------------------------------------------- /Maximum Depth of Binary Tree.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 | { 12 | public: 13 | int maxDepth(TreeNode *root) 14 | { 15 | if (root == nullptr) 16 | { 17 | return 0; 18 | } 19 | 20 | int left_depth = maxDepth(root->left); 21 | int right_depth = maxDepth(root->right); 22 | return max(left_depth, right_depth) + 1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Maximum Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxSubArray(int A[], int n) 5 | { 6 | int min = 0, max = A[0], sum = 0; 7 | for (int i = 0; i < n; ++i) 8 | { 9 | sum += A[i]; 10 | if (sum - min > max) 11 | { 12 | max = sum - min; 13 | } 14 | if (sum < min) 15 | { 16 | min = sum; 17 | } 18 | } 19 | return max; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Median of Two Sorted Arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | double findMedianSortedArrays(int A[], int m, int B[], int n) 5 | { 6 | if (m == 0) 7 | { 8 | return (B[(n - 1) /2] + B[n / 2]) / 2.0; 9 | } 10 | 11 | if (n == 0) 12 | { 13 | return (A[(m - 1) / 2] + A[m / 2]) / 2.0; 14 | } 15 | 16 | int total = m + n; 17 | int half = total / 2 + 1; 18 | int left = max(0, half - n); 19 | int right = min(m, half - 0); 20 | while (left < right) 21 | { 22 | int a = (left + right) / 2; 23 | int b = half - a; 24 | 25 | if (a == 0) 26 | { 27 | if (m == 0 || B[b-1] <= A[0]) 28 | { 29 | break; 30 | } 31 | else 32 | { 33 | left = a + 1; 34 | } 35 | continue; 36 | } 37 | 38 | if (b == 0) 39 | { 40 | if (n == 0 || A[a-1] <= B[0]) 41 | { 42 | break; 43 | } 44 | else 45 | { 46 | right = a - 1; 47 | } 48 | continue; 49 | } 50 | 51 | if (A[a - 1] >= B[b - 1]) 52 | { 53 | if (b == n || A[a - 1] <= B[b]) 54 | { 55 | break; 56 | } 57 | else 58 | { 59 | right = a - 1; 60 | } 61 | } 62 | else 63 | { 64 | if (a == m || B[b - 1] <= A[a]) 65 | { 66 | break; 67 | } 68 | else 69 | { 70 | left = a + 1; 71 | } 72 | } 73 | } 74 | 75 | int a = (left + right) / 2; 76 | int b = half - a; 77 | 78 | if (a == 0) 79 | { 80 | if (total % 2 == 1) 81 | { 82 | return B[b - 1]; 83 | } 84 | else 85 | { 86 | return (B[b - 2] + B[b - 1]) / 2.0; 87 | } 88 | } 89 | 90 | if (b == 0) 91 | { 92 | if (total % 2 == 1) 93 | { 94 | return A[a - 1]; 95 | } 96 | else 97 | { 98 | return (A[a - 2] + A[a - 1]) / 2.0; 99 | } 100 | } 101 | 102 | if (A[a - 1] >= B[b - 1]) 103 | { 104 | if (total % 2 == 1) 105 | { 106 | return A[a - 1]; 107 | } 108 | else 109 | { 110 | if (a == 1) 111 | { 112 | return (B[b - 1] + A[a - 1]) / 2.0; 113 | } 114 | else 115 | { 116 | return (max(B[b - 1], A[a - 2]) + A[a - 1]) / 2.0; 117 | } 118 | } 119 | } 120 | else 121 | { 122 | if (total % 2 == 1) 123 | { 124 | return B[b - 1]; 125 | } 126 | else 127 | { 128 | if (b == 1) 129 | { 130 | return (A[a - 1] + B[b - 1]) / 2.0; 131 | } 132 | else 133 | { 134 | return (max(A[a - 1], B[b - 2]) + B[b - 1]) / 2.0; 135 | } 136 | } 137 | } 138 | } 139 | }; 140 | -------------------------------------------------------------------------------- /Merge Intervals.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | static bool cmp(const Interval& left, const Interval& right) 14 | { 15 | return (left.start < right.start); 16 | } 17 | 18 | vector merge(vector &intervals) 19 | { 20 | vector result(intervals); 21 | if (!result.empty()) 22 | { 23 | sort(result.begin(), result.end(), cmp); 24 | auto it1 = result.begin(); 25 | auto it2 = it1 + 1; 26 | for (; it2 != result.end(); ++it2) 27 | { 28 | if (it2->start <= it1->end) 29 | { 30 | it1->end = max(it1->end, it2->end); 31 | } 32 | else 33 | { 34 | ++it1; 35 | *it1 = *it2; 36 | } 37 | } 38 | ++it1; 39 | result.erase(it1, result.end()); 40 | } 41 | return result; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Merge Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void merge(int A[], int m, int B[], int n) 5 | { 6 | int i = m + n - 1; 7 | int ai = m - 1; 8 | int bi = n - 1; 9 | while (ai >= 0 && bi >= 0) 10 | { 11 | if (A[ai] > B[bi]) 12 | { 13 | A[i--] = A[ai--]; 14 | } 15 | else 16 | { 17 | A[i--] = B[bi--]; 18 | } 19 | } 20 | if (bi >= 0) 21 | { 22 | copy(B, B + bi + 1, A); 23 | } 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Merge Two Sorted Lists.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 | { 11 | public: 12 | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) 13 | { 14 | ListNode head(0); 15 | ListNode* cur = &head; 16 | while (l1 != NULL && l2 != NULL) 17 | { 18 | if (l1->val < l2->val) 19 | { 20 | cur->next = l1; 21 | l1 = l1->next; 22 | } 23 | else 24 | { 25 | cur->next = l2; 26 | l2 = l2->next; 27 | } 28 | cur = cur->next; 29 | } 30 | 31 | if (l1 != NULL) 32 | { 33 | cur->next = l1; 34 | } 35 | 36 | if (l2 != NULL) 37 | { 38 | cur->next = l2; 39 | } 40 | 41 | return head.next; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Merge k Sorted Lists.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 | { 11 | public: 12 | ListNode *mergeKLists(vector &lists) 13 | { 14 | ListNode help(0); 15 | ListNode* cur = &help; 16 | 17 | lists.erase(remove(lists.begin(), lists.end(), nullptr), lists.end()); 18 | 19 | while (!lists.empty()) 20 | { 21 | size_t m = 0; 22 | for (size_t i = 1; i < lists.size(); ++i) 23 | { 24 | if (lists[i]->val < lists[m]->val) 25 | { 26 | m = i; 27 | } 28 | } 29 | cur->next = lists[m]; 30 | cur = cur->next; 31 | lists[m] = lists[m]->next; 32 | if (lists[m] == NULL) 33 | { 34 | lists.erase(lists.begin() + m); 35 | } 36 | } 37 | 38 | cur->next = NULL; 39 | 40 | return help.next; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Minimum Depth of Binary Tree.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 | { 12 | public: 13 | int minDepth(TreeNode *root) 14 | { 15 | if (root == nullptr) 16 | { 17 | return 0; 18 | } 19 | 20 | int left_depth = minDepth(root->left); 21 | int right_depth = minDepth(root->right); 22 | 23 | if (left_depth == 0) 24 | { 25 | if (right_depth == 0) 26 | { 27 | return 1; 28 | } 29 | else 30 | { 31 | return right_depth + 1; 32 | } 33 | } 34 | else 35 | { 36 | if (right_depth == 0) 37 | { 38 | return left_depth + 1; 39 | } 40 | else 41 | { 42 | return min(left_depth, right_depth) + 1; 43 | } 44 | } 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Minimum Path Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minPathSum(vector > &grid) 5 | { 6 | size_t row = grid.size(); 7 | size_t column = grid[0].size(); 8 | 9 | vector pathsum(column); 10 | 11 | pathsum[0] = grid[0][0]; 12 | for (size_t j = 1; j < column; ++j) 13 | { 14 | pathsum[j] = grid[0][j] + pathsum[j-1]; 15 | } 16 | 17 | for (size_t i = 1; i < row; ++i) 18 | { 19 | pathsum[0] += grid[i][0]; 20 | for (size_t j = 1; j < column; ++j) 21 | { 22 | pathsum[j] = grid[i][j] + min(pathsum[j-1], pathsum[j]); 23 | } 24 | } 25 | 26 | return pathsum[column-1]; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Minimum Window Substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string minWindow(string S, string T) 5 | { 6 | string result; 7 | 8 | vector lettercount(256, 0); 9 | for (char c : T) 10 | { 11 | lettercount[c] -= 1; 12 | } 13 | 14 | int not_contain = lettercount.size() - count(lettercount.begin(), lettercount.end(), 0); 15 | 16 | size_t left = 0; 17 | size_t right = 0; 18 | for (; right < S.size(); right += 1) 19 | { 20 | lettercount[S[right]] += 1; 21 | if (lettercount[S[right]] == 0) 22 | { 23 | not_contain -= 1; 24 | if (not_contain == 0) 25 | { 26 | while (lettercount[S[left]] > 0) 27 | { 28 | lettercount[S[left]] -= 1; 29 | left += 1; 30 | } 31 | result.assign(S, left, right + 1 - left); 32 | break; 33 | } 34 | } 35 | } 36 | 37 | while (right < S.size()) 38 | { 39 | right += 1; 40 | lettercount[S[right]] += 1; 41 | while (lettercount[S[left]] > 0) 42 | { 43 | lettercount[S[left]] -= 1; 44 | left += 1; 45 | } 46 | if (right + 1 - left < result.size()) 47 | { 48 | result.assign(S, left, right + 1 - left); 49 | } 50 | } 51 | 52 | return result; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /Multiply Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string multiply(string num1, string num2) 4 | { 5 | vector vi1(num1.size()); 6 | for (size_t i = 0; i < num1.size(); ++i) 7 | { 8 | vi1[i] = num1[i] - '0'; 9 | } 10 | reverse(vi1.begin(), vi1.end()); 11 | 12 | vector vi2(num2.size()); 13 | for (size_t i = 0; i < num2.size(); ++i) 14 | { 15 | vi2[i] = num2[i] - '0'; 16 | } 17 | reverse(vi2.begin(), vi2.end()); 18 | 19 | vector product(vi1.size() + vi2.size() - 1, 0); 20 | for (size_t i1 = 0; i1 < vi1.size(); ++i1) 21 | { 22 | for (size_t i2 = 0; i2 < vi2.size(); ++i2) 23 | { 24 | product[i1+i2] += vi1[i1] * vi2[i2]; 25 | } 26 | } 27 | 28 | for (size_t i = 1; i < product.size(); ++i) 29 | { 30 | if (product[i-1] >= 10) 31 | { 32 | product[i] += product[i-1] / 10; 33 | product[i-1] %= 10; 34 | } 35 | } 36 | 37 | if (product.back() >= 10) 38 | { 39 | int carry = product.back() / 10; 40 | product.back() %= 10; 41 | product.push_back(carry); 42 | } 43 | 44 | while (product.back() == 0) 45 | { 46 | product.pop_back(); 47 | } 48 | 49 | if (product.empty()) 50 | { 51 | product.push_back(0); 52 | } 53 | 54 | reverse(product.begin(), product.end()); 55 | 56 | string result; 57 | for (int i : product) 58 | { 59 | result.push_back('0' + i); 60 | } 61 | return result; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /N-Queens II.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | public: 5 | int totalNQueens(int n) 6 | { 7 | vector rowpos(n); 8 | int count = 0; 9 | dps(rowpos, 0, count); 10 | return count; 11 | } 12 | 13 | void dps(vector& rowpos, int row, int& count) 14 | { 15 | int n = rowpos.size(); 16 | for (int p = 0; p < n; ++p) 17 | { 18 | int i = 0; 19 | for (; i < row; ++i) 20 | { 21 | if (rowpos[i] == p || rowpos[i] + i == p + row || rowpos[i] - i == p - row) 22 | { 23 | break; 24 | } 25 | } 26 | if (i == row) 27 | { 28 | rowpos[row] = p; 29 | if (row < n - 1) 30 | { 31 | dps(rowpos, row + 1, count); 32 | } 33 | else 34 | { 35 | count += 1; 36 | } 37 | } 38 | } 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /N-Queens.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> solveNQueens(int n) 5 | { 6 | vector> q; 7 | for (int i = 0; i < n; ++i) 8 | { 9 | q.push_back(vector({i})); 10 | } 11 | for (int i = 1; i < n; ++i) 12 | { 13 | vector> temp; 14 | for (vector& x : q) 15 | { 16 | for (int p = 0; p < n; ++p) 17 | { 18 | int j = 0; 19 | for (; j < i; ++j) 20 | { 21 | if (x[j] == p || x[j] + j == p + i || x[j] - j == p - i) 22 | { 23 | break; 24 | } 25 | } 26 | if (j == i) 27 | { 28 | temp.push_back(x); 29 | temp.back().push_back(p); 30 | } 31 | } 32 | } 33 | q.swap(temp); 34 | } 35 | 36 | vector s(n, string(n, '.')); 37 | for (size_t i = 0; i < n; ++i) 38 | { 39 | s[i][i] = 'Q'; 40 | } 41 | vector> result; 42 | for (auto& x : q) 43 | { 44 | result.push_back(vector()); 45 | for (auto i : x) 46 | { 47 | result.back().push_back(s[i]); 48 | } 49 | } 50 | 51 | return result; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /Next Permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void nextPermutation(vector &num) 5 | { 6 | size_t i = num.size() - 1; 7 | for (; i > 0; --i) 8 | { 9 | if (num[i] > num[i-1]) 10 | { 11 | for (size_t j = num.size() - 1; j >= i; --j) 12 | { 13 | if (num[j] > num[i-1]) 14 | { 15 | swap(num[i-1], num[j]); 16 | break; 17 | } 18 | } 19 | break; 20 | } 21 | } 22 | 23 | reverse(num.begin() + i, num.end()); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Palindrome Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isPalindrome(int x) 5 | { 6 | if (x < 0) 7 | { 8 | return false; 9 | } 10 | 11 | int digit[12] = {0}; 12 | int count = 0; 13 | while (x != 0) 14 | { 15 | digit[count++] = x % 10; 16 | x /= 10; 17 | } 18 | 19 | for (int i = 0; i < count / 2; ++i) 20 | { 21 | if (digit[i] != digit[count - 1 - i]) 22 | { 23 | return false; 24 | } 25 | } 26 | 27 | return true; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Palindrome Partitioning II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minCut(string s) 5 | { 6 | const size_t total = s.length(); 7 | vector waiting(1, total); 8 | vector temp; 9 | vector done(total, false); 10 | size_t cut = 0; 11 | while (true) 12 | { 13 | for (size_t i = 0; i < waiting.size(); ++i) 14 | { 15 | if (isPalindrome(s, total - waiting[i], waiting[i])) 16 | { 17 | return cut; 18 | } 19 | 20 | for (size_t len = 1; len < waiting[i]; ++len) 21 | { 22 | if (!done[len] && isPalindrome(s, total - waiting[i], waiting[i] - len)) 23 | { 24 | temp.push_back(len); 25 | done[len] = true; 26 | } 27 | } 28 | } 29 | 30 | waiting.swap(temp); 31 | temp.clear(); 32 | cut += 1; 33 | } 34 | } 35 | 36 | bool isPalindrome(const string& s, size_t begin, size_t len) 37 | { 38 | for (size_t i = 0; i < len / 2; ++i) 39 | { 40 | if (s[begin + i] != s[begin + len - 1 - i]) 41 | { 42 | return false; 43 | } 44 | } 45 | return true; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Palindrome Partitioning.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> partition(string s) 5 | { 6 | vector> result; 7 | vector> partition_string({{s}}); 8 | vector> temp; 9 | while (!partition_string.empty()) 10 | { 11 | for (auto& x : partition_string) 12 | { 13 | string& untreated = x.back(); 14 | for (size_t len = 1; len < untreated.size(); ++len) 15 | { 16 | if (isPalindrome(untreated, 0, len)) 17 | { 18 | temp.push_back(x); 19 | temp.back().back().erase(len, untreated.size() - len); 20 | temp.back().push_back(untreated.substr(len, untreated.size() - len)); 21 | } 22 | } 23 | 24 | if (isPalindrome(untreated, 0, untreated.size())) 25 | { 26 | result.push_back(x); 27 | } 28 | } 29 | 30 | partition_string.swap(temp); 31 | temp.clear(); 32 | } 33 | 34 | return result; 35 | } 36 | 37 | bool isPalindrome(const string& s, size_t begin, size_t len) 38 | { 39 | for (size_t i = 0; i < len / 2; ++i) 40 | { 41 | if (s[begin + i] != s[begin + len - 1 - i]) 42 | { 43 | return false; 44 | } 45 | } 46 | return true; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Partition 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 | { 11 | public: 12 | ListNode *partition(ListNode *head, int x) 13 | { 14 | vector less; 15 | vector greater; 16 | ListNode* node = head; 17 | while (node != NULL) 18 | { 19 | if (node->val < x) 20 | { 21 | less.push_back(node->val); 22 | } 23 | else 24 | { 25 | greater.push_back(node->val); 26 | } 27 | node = node->next; 28 | } 29 | 30 | node = head; 31 | for (size_t i = 0; i < less.size(); ++i) 32 | { 33 | node->val = less[i]; 34 | node = node->next; 35 | } 36 | for (size_t i = 0; i < greater.size(); ++i) 37 | { 38 | node->val = greater[i]; 39 | node = node->next; 40 | } 41 | 42 | return head; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Pascal's Triangle II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector getRow(int rowIndex) 5 | { 6 | vector result; 7 | for (int i = 0; i <= rowIndex; ++i) 8 | { 9 | for (int j = i - 1; j >= 1; --j) 10 | { 11 | result[j] += result[j-1]; 12 | } 13 | result.push_back(1); 14 | } 15 | return result; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Pascal's Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > generate(int numRows) 5 | { 6 | vector > result; 7 | vector v; 8 | for (int i = 0; i < numRows; ++i) 9 | { 10 | for (int j = i - 1; j >= 1; --j) 11 | { 12 | v[j] += v[j-1]; 13 | } 14 | v.push_back(1); 15 | result.push_back(v); 16 | } 17 | return result; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Path Sum II.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 | { 12 | public: 13 | vector > pathSum(TreeNode* root, int sum) 14 | { 15 | vector> result; 16 | if (root != NULL) 17 | { 18 | vector path; 19 | walk(root, sum, path, result); 20 | } 21 | return result; 22 | } 23 | 24 | void walk(TreeNode* root, int sum, vector& path, vector>& result) 25 | { 26 | sum -= root->val; 27 | path.push_back(root->val); 28 | 29 | if (root->left == NULL && root->right == NULL) 30 | { 31 | if (sum == 0) 32 | { 33 | result.push_back(path); 34 | } 35 | } 36 | 37 | if (root->left != NULL) 38 | { 39 | walk(root->left, sum, path, result); 40 | } 41 | 42 | if (root->right != NULL) 43 | { 44 | walk(root->right, sum, path, result); 45 | } 46 | 47 | path.pop_back(); 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Path Sum.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 | { 12 | public: 13 | bool hasPathSum(TreeNode *root, int sum) 14 | { 15 | return (NULL != root) 16 | && ((NULL != root->left && hasPathSum(root->left, sum - root->val)) 17 | || (NULL != root->right && hasPathSum(root->right, sum - root->val)) 18 | || (NULL == root->left && NULL == root->right && sum == root->val)); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Permutation Sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string getPermutation(int n, int k) 5 | { 6 | string s; 7 | for (char c = '1'; c < '1' + n; ++c) 8 | { 9 | s.push_back(c); 10 | } 11 | 12 | int factorial = 1; 13 | for (int i = 1; i <= n; ++i) 14 | { 15 | factorial *= i; 16 | } 17 | 18 | k -= 1; 19 | 20 | string result; 21 | while (n) 22 | { 23 | factorial /= n; 24 | int index = k / factorial; 25 | k %= factorial; 26 | n -= 1; 27 | 28 | result.push_back(s[index]); 29 | s.erase(index, 1); 30 | } 31 | return result; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Permutations II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > permuteUnique(vector &num) 5 | { 6 | vector one(num); 7 | sort(one.begin(), one.end()); 8 | vector> all({one}); 9 | 10 | const size_t count = one.size(); 11 | while (true) 12 | { 13 | bool find = false; 14 | for (size_t i = count - 1; i > 0; --i) 15 | { 16 | if (one[i] > one[i-1]) 17 | { 18 | size_t j = count - 1; 19 | while (one[j] <= one[i - 1]) 20 | { 21 | --j; 22 | } 23 | 24 | swap(one[i - 1], one[j]); 25 | reverse(one.begin() + i, one.end()); 26 | all.push_back(one); 27 | 28 | find = true; 29 | break; 30 | } 31 | } 32 | if (!find) 33 | { 34 | break; 35 | } 36 | } 37 | 38 | return all; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Permutations.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > permute(vector &num) 5 | { 6 | vector one(num); 7 | vector> all({one}); 8 | 9 | vector p; 10 | for (size_t i = 0; i < num.size(); ++i) 11 | { 12 | p.push_back(i); 13 | } 14 | 15 | while (next_permutation(p.begin(), p.end())) 16 | { 17 | for (size_t i = 0; i < num.size(); ++i) 18 | { 19 | one[i] = num[p[i]]; 20 | } 21 | all.push_back(one); 22 | } 23 | 24 | return all; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Plus One.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector plusOne(vector &digits) 5 | { 6 | vector result = digits; 7 | result[result.size() - 1] += 1; 8 | for (size_t i = result.size() - 1; i > 0; --i) 9 | { 10 | if (result[i] == 10) 11 | { 12 | result[i] = 0; 13 | result[i-1] += 1; 14 | } 15 | } 16 | if (result[0] == 10) 17 | { 18 | result[0] = 0; 19 | result.insert(result.begin(), 1); 20 | } 21 | return result; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Populating Next Right Pointers in Each Node II.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree with next pointer. 3 | * struct TreeLinkNode { 4 | * int val; 5 | * TreeLinkNode *left, *right, *next; 6 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution 10 | { 11 | public: 12 | void connect(TreeLinkNode *root) 13 | { 14 | if (root != nullptr) 15 | { 16 | vector level({root}); 17 | vector level_temp; 18 | while (!level.empty()) 19 | { 20 | for (size_t i = 0; i < level.size() - 1; ++i) 21 | { 22 | level[i]->next = level[i+1]; 23 | } 24 | level.back()->next = nullptr; 25 | 26 | for (auto p : level) 27 | { 28 | if (p->left != nullptr) 29 | { 30 | level_temp.push_back(p->left); 31 | } 32 | if (p->right != nullptr) 33 | { 34 | level_temp.push_back(p->right); 35 | } 36 | } 37 | 38 | level.swap(level_temp); 39 | level_temp.clear(); 40 | } 41 | } 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Populating Next Right Pointers in Each Node.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree with next pointer. 3 | * struct TreeLinkNode { 4 | * int val; 5 | * TreeLinkNode *left, *right, *next; 6 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution 10 | { 11 | public: 12 | void connect(TreeLinkNode *root) 13 | { 14 | if (root != nullptr) 15 | { 16 | vector level({root}); 17 | vector level_temp; 18 | while (!level.empty()) 19 | { 20 | for (size_t i = 0; i < level.size() - 1; ++i) 21 | { 22 | level[i]->next = level[i+1]; 23 | } 24 | level.back()->next = nullptr; 25 | 26 | for (auto p : level) 27 | { 28 | if (p->left != nullptr) 29 | { 30 | level_temp.push_back(p->left); 31 | } 32 | if (p->right != nullptr) 33 | { 34 | level_temp.push_back(p->right); 35 | } 36 | } 37 | 38 | level.swap(level_temp); 39 | level_temp.clear(); 40 | } 41 | } 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Pow(x, n).cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | double pow(double x, int n) 5 | { 6 | if (n < 0) 7 | { 8 | x = 1.0 / x; 9 | } 10 | 11 | double result = 1.0; 12 | double power = x; 13 | 14 | while (n != 0) 15 | { 16 | if (n % 2 != 0) 17 | { 18 | result *= power; 19 | } 20 | n /= 2; 21 | power = power * power; 22 | } 23 | 24 | return result; 25 | } 26 | }; 27 | 28 | //====================================================================== 29 | 30 | class Solution2 31 | { 32 | public: 33 | double pow(double x, int n) 34 | { 35 | if (n == 0) 36 | { 37 | return 1.0; 38 | } 39 | 40 | int h = n / 2; 41 | int r = n - h * 2; 42 | 43 | double result = pow(x, h); 44 | result *= result; 45 | if (r == 1) 46 | { 47 | return result * x; 48 | } 49 | else if (r == 0) 50 | { 51 | return result; 52 | } 53 | else 54 | { 55 | return result / x; 56 | } 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | fuwutu@qq.com 2 | -------------------------------------------------------------------------------- /Recover Binary Search Tree.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 | { 12 | public: 13 | void recoverTree(TreeNode *root) 14 | { 15 | TreeNode* p = root; 16 | TreeNode* prev = nullptr; 17 | TreeNode* cur = nullptr; 18 | TreeNode* mistake1 = nullptr; 19 | TreeNode* mistake2 = nullptr; 20 | while (p != nullptr) 21 | { 22 | if (p->left == nullptr) 23 | { 24 | prev = cur; 25 | cur = p; 26 | if (prev != nullptr && prev->val > cur->val) 27 | { 28 | if (mistake1 == nullptr) 29 | { 30 | mistake1 = prev; 31 | } 32 | mistake2 = cur; 33 | } 34 | p = p->right; 35 | } 36 | else 37 | { 38 | TreeNode* temp = p->left; 39 | while (temp->right != nullptr && temp->right != p) 40 | { 41 | temp = temp->right; 42 | } 43 | if (temp->right == nullptr) 44 | { 45 | temp->right = p; 46 | p = p->left; 47 | } 48 | else 49 | { 50 | prev = cur; 51 | cur = p; 52 | if (prev != nullptr && prev->val > cur->val) 53 | { 54 | if (mistake1 == nullptr) 55 | { 56 | mistake1 = prev; 57 | } 58 | mistake2 = cur; 59 | } 60 | temp->right = nullptr; 61 | p = p->right; 62 | } 63 | } 64 | } 65 | 66 | swap(mistake1->val, mistake2->val); 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /Regular Expression Matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isMatch(const char *s, const char *p) 5 | { 6 | set match({const_cast(s)}); 7 | set temp; 8 | while (*p != '\0' && !match.empty()) 9 | { 10 | if (p[0] == '.') 11 | { 12 | if (p[1] == '*') 13 | { 14 | auto m = *(match.begin()); 15 | temp.insert(m); 16 | while (*m != '\0') 17 | { 18 | temp.insert(++m); 19 | } 20 | p = p + 2; 21 | } 22 | else 23 | { 24 | for (char* m : match) 25 | { 26 | if (*m != '\0') 27 | { 28 | temp.insert(m + 1); 29 | } 30 | } 31 | p = p + 1; 32 | } 33 | } 34 | else 35 | { 36 | if (p[1] == '*') 37 | { 38 | for (char* m : match) 39 | { 40 | temp.insert(m); 41 | while (*m == *p) 42 | { 43 | temp.insert(++m); 44 | } 45 | } 46 | p = p + 2; 47 | } 48 | else 49 | { 50 | for (char* m : match) 51 | { 52 | if (*m == *p) 53 | { 54 | temp.insert(m + 1); 55 | } 56 | } 57 | p = p + 1; 58 | } 59 | } 60 | 61 | match.swap(temp); 62 | temp.clear(); 63 | } 64 | 65 | return (!match.empty() && *(*(match.rbegin())) == '\0'); 66 | } 67 | }; 68 | -------------------------------------------------------------------------------- /Remove Duplicates from Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int removeDuplicates(int A[], int n) 5 | { 6 | if (n <= 2) 7 | { 8 | return n; 9 | } 10 | 11 | int length = 2; 12 | for (int i = 2; i < n; ++i) 13 | { 14 | if (A[i] != A[length - 1] || A[i] != A[length - 2]) 15 | { 16 | A[length++] = A[i]; 17 | } 18 | } 19 | return length; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Remove Duplicates from Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int removeDuplicates(int A[], int n) 5 | { 6 | int new_length = min(n, 1); 7 | for (int i = 1; i < n; ++i) 8 | { 9 | if (A[i] != A[i-1]) 10 | { 11 | A[new_length++] = A[i]; 12 | } 13 | } 14 | 15 | return new_length; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Remove Duplicates from Sorted List 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 | { 11 | public: 12 | ListNode *deleteDuplicates(ListNode *head) 13 | { 14 | ListNode help(0); 15 | help.next = head; 16 | ListNode* cur = &help; 17 | while (cur != NULL) 18 | { 19 | if (cur->next != NULL && cur->next->next != NULL && cur->next->val == cur->next->next->val) 20 | { 21 | int val = cur->next->val; 22 | ListNode* next = cur->next->next->next; 23 | while (next != NULL && next->val == val) 24 | { 25 | next = next->next; 26 | } 27 | cur->next = next; 28 | } 29 | else 30 | { 31 | cur = cur->next; 32 | } 33 | } 34 | 35 | return help.next; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Remove Duplicates from Sorted 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 | { 11 | public: 12 | ListNode *deleteDuplicates(ListNode *head) 13 | { 14 | ListNode* cur = head; 15 | while (NULL != cur) 16 | { 17 | ListNode* next = cur->next; 18 | if ((NULL != next) && (cur->val == next->val)) 19 | { 20 | cur->next = next->next; 21 | } 22 | else 23 | { 24 | cur = cur->next; 25 | } 26 | } 27 | return head; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Remove Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int removeElement(int A[], int n, int elem) 5 | { 6 | int new_length = 0; 7 | for (int i = 0; i < n; ++i) 8 | { 9 | if (A[i] != elem) 10 | { 11 | A[new_length++] = A[i]; 12 | } 13 | } 14 | 15 | return new_length; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Remove Nth Node From End of 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 | { 11 | public: 12 | ListNode *removeNthFromEnd(ListNode *head, int n) 13 | { 14 | ListNode* node = head; 15 | int count = 1; 16 | while (node->next != NULL) 17 | { 18 | node = node->next; 19 | ++count; 20 | } 21 | 22 | if (count == n) 23 | { 24 | return head->next; 25 | } 26 | 27 | node = head; 28 | for (int i = 0; i < count - n - 1; ++i) 29 | { 30 | node = node->next; 31 | } 32 | node->next = node->next->next; 33 | return head; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Restore IP Addresses.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector restoreIpAddresses(string s) 5 | { 6 | vector ips; 7 | string ip1, ip2, ip3, ip4; 8 | int total_len = s.length(); 9 | for (int len1 = 1; len1 <= min(3, total_len - 3); ++len1) 10 | { 11 | ip1 = s.substr(0, len1); 12 | int num1 = atoi(ip1.c_str()); 13 | if ((len1 > 1 && s[0] == '0') || num1 > 255) 14 | { 15 | break; 16 | } 17 | for (int len2 = 1; len2 <= min(3, total_len - len1 - 2); ++len2) 18 | { 19 | ip2 = s.substr(len1, len2); 20 | int num2 = atoi(ip2.c_str()); 21 | if ((len2 > 1 && s[len1] == '0') || num2 > 255) 22 | { 23 | break; 24 | } 25 | for (int len3 = 1; len3 <= min(3, total_len - len1 - len2 -1); ++len3) 26 | { 27 | 28 | ip3 = s.substr(len1 + len2, len3); 29 | int num3 = atoi(ip3.c_str()); 30 | if ((len3 > 1 && s[len1 + len2] == '0') || num3 > 255) 31 | { 32 | break; 33 | } 34 | int len4 = total_len - len1 - len2 - len3; 35 | if (len4 <= 3) 36 | { 37 | ip4 = s.substr(len1 + len2 + len3, len4); 38 | int num4 = atoi(ip4.c_str()); 39 | if (!(len4 > 1 && s[len1 + len2 + len3] == '0') && num4 <= 255) 40 | { 41 | ips.push_back(ip1 + "." + ip2 + "." + ip3 + "." + ip4); 42 | } 43 | } 44 | } 45 | } 46 | } 47 | return ips; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Reverse Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int reverse(int x) 5 | { 6 | int n = 0; 7 | while (x != 0) 8 | { 9 | n = n * 10 + x % 10; 10 | x /= 10; 11 | } 12 | return n; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Reverse Linked List 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 | { 11 | public: 12 | ListNode *reverseBetween(ListNode *head, int m, int n) 13 | { 14 | if (m < n) 15 | { 16 | ListNode help(0); 17 | help.next = head; 18 | 19 | ListNode* left = &help; 20 | for (int i = 1; i < m; ++i) 21 | { 22 | left = left->next; 23 | } 24 | 25 | ListNode* rend = left->next; 26 | ListNode* middle = rend; 27 | ListNode* rbegin = rend->next; 28 | ListNode* right = rbegin->next; 29 | for (int i = 1; i < n - m; ++i) 30 | { 31 | rbegin->next = middle; 32 | middle = rbegin; 33 | rbegin = right; 34 | right = right->next; 35 | } 36 | rbegin->next = middle; 37 | 38 | left->next = rbegin; 39 | rend->next = right; 40 | 41 | head = help.next; 42 | } 43 | return head; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Reverse Nodes in k-Group.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 | { 11 | public: 12 | ListNode *reverseKGroup(ListNode *head, int k) 13 | { 14 | ListNode help(0); 15 | help.next = head; 16 | if (k >= 2) 17 | { 18 | ListNode* left = &help; 19 | ListNode* cur = head; 20 | while (cur != NULL && cur->next != NULL) 21 | { 22 | ListNode* rbegin = cur; 23 | ListNode* rend = cur; 24 | cur = cur->next; 25 | rend->next = NULL; 26 | int count = 2; 27 | while (count < k && cur->next != NULL) 28 | { 29 | ListNode* temp = cur->next; 30 | cur->next = rbegin; 31 | rbegin = cur; 32 | cur = temp; 33 | ++count; 34 | } 35 | 36 | if (count == k) 37 | { 38 | rend->next = cur->next; 39 | cur->next = rbegin; 40 | left->next = cur; 41 | left = rend; 42 | cur = rend->next; 43 | } 44 | else 45 | { 46 | while (rbegin != NULL) 47 | { 48 | ListNode* temp = rbegin; 49 | rbegin = rbegin->next; 50 | temp->next = cur; 51 | cur = temp; 52 | } 53 | left->next = rend; 54 | cur = NULL; 55 | } 56 | } 57 | } 58 | return help.next; 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /Roman to Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int romanToInt(string s) 5 | { 6 | const string one[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 7 | const string ten[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 8 | const string hundred[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 9 | const string thousand[] = {"", "M", "MM", "MMM"}; 10 | 11 | int num = 0; 12 | for (size_t i = sizeof(thousand) / sizeof(thousand[0]) - 1; i > 0; --i) 13 | { 14 | size_t len = thousand[i].length(); 15 | if (s.length() >= len && s.substr(0, len) == thousand[i]) 16 | { 17 | num += i * 1000; 18 | s.erase(0, len); 19 | break; 20 | } 21 | } 22 | 23 | for (size_t i = sizeof(hundred) / sizeof(hundred[0]) - 1; i > 0; --i) 24 | { 25 | size_t len = hundred[i].length(); 26 | if (s.length() >= len && s.substr(0, len) == hundred[i]) 27 | { 28 | num += i * 100; 29 | s.erase(0, len); 30 | break; 31 | } 32 | } 33 | 34 | for (size_t i = sizeof(ten) / sizeof(ten[0]) - 1; i > 0; --i) 35 | { 36 | size_t len = ten[i].length(); 37 | if (s.length() >= len && s.substr(0, len) == ten[i]) 38 | { 39 | num += i * 10; 40 | s.erase(0, len); 41 | break; 42 | } 43 | } 44 | 45 | for (size_t i = sizeof(one) / sizeof(one[0]) - 1; i > 0; --i) 46 | { 47 | size_t len = one[i].length(); 48 | if (s.length() >= len && s.substr(0, len) == one[i]) 49 | { 50 | num += i * 1; 51 | s.erase(0, len); 52 | break; 53 | } 54 | } 55 | 56 | return num; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /Rotate Image.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void rotate(vector > &matrix) 5 | { 6 | size_t n = matrix.size(); 7 | for (size_t i = 0; i < (n + 1) / 2; ++i) 8 | { 9 | for (size_t j = 0; j < n / 2; ++j) 10 | { 11 | int temp = matrix[i][j]; 12 | matrix[i][j] = matrix[n - 1 - j][i]; 13 | matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]; 14 | matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]; 15 | matrix[j][n - 1 - i] = temp; 16 | } 17 | } 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Rotate 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 | { 11 | public: 12 | ListNode* rotateRight(ListNode* head, int k) 13 | { 14 | ListNode dummy(0); 15 | dummy.next = head; 16 | 17 | ListNode* cur = head; 18 | int count = 0; 19 | while (cur != nullptr) 20 | { 21 | cur = cur->next; 22 | count += 1; 23 | } 24 | 25 | if (count != 0) 26 | { 27 | int r = k % count; 28 | if (r != 0) 29 | { 30 | r = count - r; 31 | cur = head; 32 | for (int i = 1; i < r; ++i) 33 | { 34 | cur = cur->next; 35 | } 36 | ListNode* first = cur->next; 37 | cur->next = nullptr; 38 | 39 | cur = first; 40 | for (int i = r + 1; i < count; ++i) 41 | { 42 | cur = cur->next; 43 | } 44 | 45 | cur->next = head; 46 | dummy.next = first; 47 | } 48 | } 49 | 50 | return dummy.next; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /Same Tree.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 | { 12 | public: 13 | bool isSameTree(TreeNode *p, TreeNode *q) 14 | { 15 | if (NULL == p && NULL == q) 16 | { 17 | return true; 18 | } 19 | 20 | return (NULL != p && NULL != q 21 | && p->val == q->val 22 | && isSameTree(p->left, q->left) && isSameTree(p->right, q->right)); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Scramble String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isScramble(string s1, string s2) 4 | { 5 | if (s1.length() != s2.length()) 6 | { 7 | return false; 8 | } 9 | 10 | if (s1 == s2) 11 | { 12 | return true; 13 | } 14 | 15 | string r1 = s1; 16 | sort(r1.begin(), r1.end()); 17 | 18 | string r2 = s2; 19 | sort(r2.begin(), r2.end()); 20 | 21 | if (r1 != r2) 22 | { 23 | return false; 24 | } 25 | 26 | for (size_t n = 1; n < s1.length(); ++n) 27 | { 28 | if (isScramble(s1.substr(0, n), s2.substr(0, n)) 29 | && isScramble(s1.substr(n, s1.length() - n), s2.substr(n, s2.length() - n))) 30 | { 31 | return true; 32 | } 33 | 34 | if (isScramble(s1.substr(0, n), s2.substr(s2.length() - n, n)) 35 | && isScramble(s1.substr(n, s1.length() - n), s2.substr(0, s2.length() - n))) 36 | { 37 | return true; 38 | } 39 | } 40 | 41 | return false; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int searchInsert(int A[], int n, int target) 5 | { 6 | for (int i = 0; i < n; ++i) 7 | { 8 | if (A[i] >= target) 9 | { 10 | return i; 11 | } 12 | } 13 | return n; 14 | } 15 | }; 16 | 17 | class Solution2 18 | { 19 | public: 20 | int searchInsert(int A[], int n, int target) 21 | { 22 | int left = 0; 23 | int right = n; 24 | while (left < right) 25 | { 26 | int middle = (left + right) / 2; 27 | if (A[middle] >= target) 28 | { 29 | right = middle; 30 | } 31 | else 32 | { 33 | left = middle + 1; 34 | } 35 | } 36 | return left; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Search a 2D Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool searchMatrix(vector > &matrix, int target) 5 | { 6 | for (size_t i = 0; i < matrix.size(); ++i) 7 | { 8 | for (size_t j = 0; j < matrix[i].size(); ++j) 9 | { 10 | if (matrix[i][j] == target) 11 | { 12 | return true; 13 | } 14 | } 15 | } 16 | return false; 17 | } 18 | }; 19 | 20 | class Solution2 21 | { 22 | public: 23 | bool searchMatrix(vector > &matrix, int target) 24 | { 25 | const int row = matrix.size(); 26 | const int column = matrix[0].size(); 27 | int left = 0; 28 | int right = row * column; 29 | while (left < right) 30 | { 31 | int middle = (left + right) / 2; 32 | int value = matrix[middle / column][middle % column]; 33 | if (value == target) 34 | { 35 | return true; 36 | } 37 | if (value < target) 38 | { 39 | left = middle + 1; 40 | } 41 | else 42 | { 43 | right = middle; 44 | } 45 | } 46 | return false; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Search for a Range.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector searchRange(int A[], int n, int target) 5 | { 6 | vector v; 7 | for (int i = 0; i < n; ++i) 8 | { 9 | v.push_back(A[i]); 10 | } 11 | auto lower = lower_bound(v.begin(), v.end(), target); 12 | auto upper = upper_bound(v.begin(), v.end(), target); 13 | 14 | if (lower == v.end() || *lower != target) 15 | { 16 | return vector({-1, -1}); 17 | } 18 | else 19 | { 20 | return vector({lower - v.begin(), upper - v.begin() - 1}); 21 | } 22 | } 23 | }; 24 | 25 | class Solution2 26 | { 27 | public: 28 | vector searchRange(int A[], int n, int target) 29 | { 30 | int left = 0; 31 | int right = n; 32 | while (left < right) 33 | { 34 | int middle = (left + right) / 2; 35 | if (A[middle] < target) 36 | { 37 | left = middle + 1; 38 | } 39 | else 40 | { 41 | right = middle; 42 | } 43 | } 44 | 45 | if (left >= 0 && left < n && A[left] == target) 46 | { 47 | int lowerbound = left; 48 | right = n; 49 | while (left < right) 50 | { 51 | int middle = (left + right) / 2; 52 | if (A[middle] <= target) 53 | { 54 | left = middle + 1; 55 | } 56 | else 57 | { 58 | right = middle; 59 | } 60 | } 61 | int upperbound = left - 1; 62 | return vector({lowerbound, upperbound}); 63 | } 64 | else 65 | { 66 | return vector({-1, -1}); 67 | } 68 | } 69 | }; 70 | -------------------------------------------------------------------------------- /Search in Rotated Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool search(int A[], int n, int target) 5 | { 6 | for (int i = 0; i < n; ++i) 7 | { 8 | if (A[i] == target) 9 | { 10 | return true; 11 | } 12 | } 13 | return false; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Search in Rotated Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int search(int A[], int n, int target) 5 | { 6 | if (n == 0) 7 | { 8 | return -1; 9 | } 10 | 11 | if (n == 1) 12 | { 13 | return A[0] == target ? 0 : -1; 14 | } 15 | 16 | if (A[0] < A[n-1]) 17 | { 18 | return search(A, 0, n, target); 19 | } 20 | 21 | int left = 1; 22 | int right = n; 23 | int middle; 24 | while (left < right) 25 | { 26 | middle = (left + right) / 2; 27 | if (A[middle] > A[0]) 28 | { 29 | left = middle + 1; 30 | } 31 | else if (A[middle] > A[middle - 1]) 32 | { 33 | right = middle; 34 | } 35 | else 36 | { 37 | break; 38 | } 39 | } 40 | 41 | if (target >= A[0]) 42 | { 43 | return search(A, 0, middle, target); 44 | } 45 | else 46 | { 47 | return search(A, middle, n, target); 48 | } 49 | } 50 | 51 | int search(int A[], int start, int end, int target) 52 | { 53 | while (start < end) 54 | { 55 | int middle = (start + end) / 2; 56 | if (A[middle] < target) 57 | { 58 | start = middle + 1; 59 | } 60 | else if (A[middle] > target) 61 | { 62 | end = middle; 63 | } 64 | else 65 | { 66 | return middle; 67 | } 68 | } 69 | 70 | return -1; 71 | } 72 | }; 73 | -------------------------------------------------------------------------------- /Set Matrix Zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void setZeroes(vector> &matrix) 5 | { 6 | int rows = matrix.size(); 7 | int columns = matrix[0].size(); 8 | 9 | vector rowshavezero; 10 | vector columnshavezero; 11 | 12 | for (int r = 0; r < rows; ++r) 13 | { 14 | for (int c = 0; c < columns; ++c) 15 | { 16 | if (matrix[r][c] == 0) 17 | { 18 | rowshavezero.push_back(r); 19 | columnshavezero.push_back(c); 20 | } 21 | } 22 | } 23 | 24 | for (int r : rowshavezero) 25 | { 26 | for (int c = 0; c < columns; ++c) 27 | { 28 | matrix[r][c] = 0; 29 | } 30 | } 31 | 32 | for (int c : columnshavezero) 33 | { 34 | for (int r = 0; r < rows; ++r) 35 | { 36 | matrix[r][c] = 0; 37 | } 38 | } 39 | } 40 | }; 41 | 42 | //============================================================================= 43 | 44 | class Solution2 45 | { 46 | public: 47 | void setZeroes(vector> &matrix) 48 | { 49 | int rows = matrix.size(); 50 | int columns = matrix[0].size(); 51 | 52 | bool firstRowHasZero(false); 53 | bool firstColumnHasZero(false); 54 | 55 | for (int c = 0; c < columns; ++c) 56 | { 57 | if (matrix[0][c] == 0) 58 | { 59 | firstRowHasZero = true; 60 | break; 61 | } 62 | } 63 | 64 | for (int r = 0; r < rows; ++r) 65 | { 66 | if (matrix[r][0] == 0) 67 | { 68 | firstColumnHasZero = true; 69 | } 70 | } 71 | 72 | for (int r = 1; r < rows; ++r) 73 | { 74 | for (int c = 1; c < columns; ++c) 75 | { 76 | if (matrix[r][c] == 0) 77 | { 78 | matrix[r][0] = 0; 79 | matrix[0][c] = 0; 80 | } 81 | } 82 | } 83 | 84 | for (int c = 1; c < columns; ++c) 85 | { 86 | if (matrix[0][c] == 0) 87 | { 88 | for (int r = 1; r < rows; ++r) 89 | { 90 | matrix[r][c] = 0; 91 | } 92 | } 93 | } 94 | 95 | for (int r = 1; r < rows; ++r) 96 | { 97 | if (matrix[r][0] == 0) 98 | { 99 | for (int c = 1; c < columns; ++c) 100 | { 101 | matrix[r][c] = 0; 102 | } 103 | } 104 | } 105 | 106 | if (firstRowHasZero) 107 | { 108 | for (int c = 0; c < columns; ++c) 109 | { 110 | matrix[0][c] = 0; 111 | } 112 | } 113 | 114 | if (firstColumnHasZero) 115 | { 116 | for (int r = 0; r < rows; ++r) 117 | { 118 | matrix[r][0] = 0; 119 | } 120 | } 121 | } 122 | }; 123 | -------------------------------------------------------------------------------- /Simplify Path.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string simplifyPath(string path) 4 | { 5 | vector directories; 6 | string directory; 7 | size_t begin = 0; 8 | while (begin + 1 < path.size()) 9 | { 10 | size_t end = path.find("/", begin + 1); 11 | if (end == string::npos) 12 | { 13 | end = path.size(); 14 | } 15 | directory.assign(path, begin, end - begin); 16 | 17 | if (directory == "/..") 18 | { 19 | if (!directories.empty()) 20 | { 21 | directories.pop_back(); 22 | } 23 | } 24 | else if (directory.compare("/") != 0 && directory.compare("/.") != 0) 25 | { 26 | directories.push_back(directory); 27 | } 28 | 29 | if (end == string::npos) 30 | { 31 | break; 32 | } 33 | begin = end; 34 | } 35 | 36 | string simplepath; 37 | for (string& directory : directories) 38 | { 39 | simplepath.append(directory); 40 | } 41 | if (simplepath.empty()) 42 | { 43 | simplepath.append("/"); 44 | } 45 | 46 | return simplepath; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Single Number II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int singleNumber(int A[], int n) 5 | { 6 | int bit3[21] = {0}; 7 | for (int i = 0; i < n; ++i) 8 | { 9 | unsigned x(static_cast(A[i])), k(0); 10 | while (x != 0) 11 | { 12 | bit3[k] += x % 3; 13 | x /= 3; 14 | k += 1; 15 | } 16 | } 17 | unsigned answer = 0; 18 | for (int i = sizeof(bit3) / sizeof(bit3[0]); i >= 0; --i) 19 | { 20 | answer = answer * 3 + bit3[i] % 3; 21 | } 22 | return static_cast(answer); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Single Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int singleNumber(int A[], int n) 5 | { 6 | int answer = 0; 7 | for (int i = 0; i < n; ++i) 8 | { 9 | answer ^= A[i]; 10 | } 11 | return answer; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Sort Colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void sortColors(int A[], int n) 5 | { 6 | int count[3] = {0, 0, 0}; 7 | for (int i = 0; i < n; ++i) 8 | { 9 | count[A[i]] += 1; 10 | } 11 | int k = 0; 12 | for (int color = 0; color <= 2; ++color) 13 | { 14 | for (int j = 0; j < count[color]; ++j) 15 | { 16 | A[k++] = color; 17 | } 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Spiral Matrix II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> generateMatrix(int n) 5 | { 6 | vector> matrix(n, vector(n)); 7 | 8 | int start = 1; 9 | int count = n - 1; 10 | for (int i = 0; i < n / 2; ++i) 11 | { 12 | for (int j = 0; j < count; ++j) 13 | { 14 | matrix[i][i+j] = start + j; 15 | matrix[i+j][n-1-i] = matrix[i][i+j] + count; 16 | matrix[n-1-i][n-1-i-j] = matrix[i+j][n-1-i] + count; 17 | matrix[n-1-i-j][i] = matrix[n-1-i][n-1-i-j] + count; 18 | } 19 | start += count * 4; 20 | count -= 2; 21 | } 22 | 23 | if (n % 2 == 1) 24 | { 25 | matrix[n/2][n/2] = start; 26 | } 27 | 28 | return matrix; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Spiral Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector spiralOrder(vector>& matrix) 4 | { 5 | vector result; 6 | if (!matrix.empty()) 7 | { 8 | int top = 0; 9 | int bottom = matrix.size() - 1; 10 | int left = 0; 11 | int right = matrix[0].size() - 1; 12 | while (true) 13 | { 14 | for (int c = left; c <= right; ++c) 15 | { 16 | result.push_back(matrix[top][c]); 17 | } 18 | top += 1; 19 | if (top > bottom) 20 | { 21 | break; 22 | } 23 | 24 | for (int r = top; r <= bottom; ++r) 25 | { 26 | result.push_back(matrix[r][right]); 27 | } 28 | right -= 1; 29 | if (left > right) 30 | { 31 | break; 32 | } 33 | 34 | for (int c = right; c >= left; --c) 35 | { 36 | result.push_back(matrix[bottom][c]); 37 | } 38 | bottom -= 1; 39 | if (top > bottom) 40 | { 41 | break; 42 | } 43 | 44 | for (int r = bottom; r >= top; --r) 45 | { 46 | result.push_back(matrix[r][left]); 47 | } 48 | left += 1; 49 | if (left > right) 50 | { 51 | break; 52 | } 53 | } 54 | } 55 | return result; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int sqrt(int x) 5 | { 6 | int square = 0; 7 | int n = 0; 8 | while (x - n - n - 1 >= square) 9 | { 10 | square += n + n + 1; 11 | ++n; 12 | } 13 | return n; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /String to Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int atoi(const char *str) 5 | { 6 | int result = 0; 7 | bool negative = false; 8 | 9 | while (isspace(*str)) 10 | { 11 | ++str; 12 | } 13 | 14 | if (*str == '+') 15 | { 16 | negative = false; 17 | ++str; 18 | } 19 | else if (*str == '-') 20 | { 21 | negative = true; 22 | ++str; 23 | } 24 | 25 | if (negative) 26 | { 27 | while (isdigit(*str)) 28 | { 29 | int n = *str - '0'; 30 | 31 | if (result < std::numeric_limits::min() / 10) 32 | { 33 | result = std::numeric_limits::min(); 34 | break; 35 | } 36 | result *= 10; 37 | 38 | if (result < std::numeric_limits::min() + n) 39 | { 40 | result = std::numeric_limits::min(); 41 | break; 42 | } 43 | result -= n; 44 | 45 | ++str; 46 | } 47 | } 48 | else 49 | { 50 | while (isdigit(*str)) 51 | { 52 | int n = *str - '0'; 53 | 54 | if (result > std::numeric_limits::max() / 10) 55 | { 56 | result = std::numeric_limits::max(); 57 | break; 58 | } 59 | result *= 10; 60 | 61 | if (result > std::numeric_limits::max() - n) 62 | { 63 | result = std::numeric_limits::max(); 64 | break; 65 | } 66 | result += n; 67 | 68 | ++str; 69 | } 70 | } 71 | 72 | return result; 73 | } 74 | }; 75 | -------------------------------------------------------------------------------- /Subsets II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > subsetsWithDup(vector &S) 5 | { 6 | sort(S.begin(), S.end()); 7 | vector> result(1, vector()); 8 | for (auto it = S.begin(); it != S.end();) 9 | { 10 | auto it2 = it; 11 | while (it2 != S.end() && *it2 == *it) 12 | { 13 | ++it2; 14 | } 15 | int value = *it; 16 | int count = it2 - it; 17 | it = it2; 18 | 19 | size_t s = result.size(); 20 | for (size_t i = 0; i < s; ++i) 21 | { 22 | vector subset = result[i]; 23 | for (int c = 0; c < count; ++c) 24 | { 25 | subset.push_back(value); 26 | result.push_back(subset); 27 | } 28 | } 29 | } 30 | return result; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > subsets(vector &S) 5 | { 6 | vector s = S; 7 | sort(s.begin(), s.end()); 8 | 9 | vector > result; 10 | result.push_back(vector()); 11 | 12 | size_t count = 1; 13 | for (size_t i = 0; i < s.size(); ++i) 14 | { 15 | for (size_t j = 0; j < count; ++j) 16 | { 17 | result.push_back(result[j]); 18 | result[count+j].push_back(s[i]); 19 | } 20 | count *= 2; 21 | } 22 | return result; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Substring with Concatenation of All Words.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector findSubstring(string S, vector &L) 5 | { 6 | const size_t count = L.size(); 7 | const size_t len = L[0].length(); 8 | const size_t total_len = len * count; 9 | 10 | vector result; 11 | if (S.length() >= total_len) 12 | { 13 | unordered_map word2count; 14 | for (auto s : L) 15 | { 16 | word2count[s] = word2count[s] + 1; 17 | } 18 | 19 | string word; 20 | for (size_t start = 0; start < len; ++start) 21 | { 22 | if (start + total_len <= S.length()) 23 | { 24 | auto word2require = word2count; 25 | size_t not_enough = word2count.size(); 26 | size_t num = 0; 27 | size_t b = start; 28 | while (b + len <= S.length()) 29 | { 30 | if (num == count) 31 | { 32 | word.assign(S, b - total_len, len); 33 | auto it = word2require.find(word); // i am sure it is not equal to word2require.end() 34 | if (it->second == 0) 35 | { 36 | not_enough += 1; 37 | } 38 | it->second += 1; 39 | num -= 1; 40 | } 41 | 42 | word.assign(S, b, len); 43 | b += len; 44 | num += 1; 45 | 46 | auto it = word2require.find(word); 47 | if (it != word2require.end()) 48 | { 49 | it->second -= 1; 50 | if (it->second == 0) 51 | { 52 | not_enough -= 1; 53 | if (not_enough == 0) 54 | { 55 | result.push_back(b - total_len); 56 | } 57 | } 58 | } 59 | else 60 | { 61 | if (b + total_len > S.length()) 62 | { 63 | break; 64 | } 65 | 66 | if (num != 1) 67 | { 68 | word2require = word2count; 69 | } 70 | not_enough = word2count.size(); 71 | num = 0; 72 | } 73 | 74 | } 75 | } 76 | } 77 | } 78 | 79 | return result; 80 | } 81 | }; 82 | 83 | //============================================================================= 84 | 85 | class Solution2 86 | { 87 | public: 88 | vector findSubstring(string S, vector &L) 89 | { 90 | const size_t count = L.size(); 91 | const size_t len = L[0].length(); 92 | const size_t total_len = len * count; 93 | 94 | vector result; 95 | if (S.length() >= total_len) 96 | { 97 | unordered_map word2count; 98 | for (auto s : L) 99 | { 100 | word2count[s] = word2count[s] + 1; 101 | } 102 | 103 | size_t not_enough = word2count.size(); 104 | list::iterator> lst; 105 | string word; 106 | 107 | for (size_t start = 0; start < len; ++start) 108 | { 109 | if (start + total_len <= S.length()) 110 | { 111 | size_t b = start; 112 | while (true) 113 | { 114 | if (b + len > S.length()) 115 | { 116 | for (auto it : lst) 117 | { 118 | it->second += 1; 119 | } 120 | lst.clear(); 121 | not_enough = word2count.size(); 122 | break; 123 | } 124 | 125 | if (lst.size() == count) 126 | { 127 | auto it = lst.front(); 128 | if (it->second == 0) 129 | { 130 | not_enough += 1; 131 | } 132 | it->second += 1; 133 | lst.pop_front(); 134 | } 135 | 136 | word.assign(S, b, len); 137 | b += len; 138 | 139 | auto it = word2count.find(word); 140 | if (it != word2count.end()) 141 | { 142 | it->second -= 1; 143 | if (it->second == 0) 144 | { 145 | not_enough -= 1; 146 | if (not_enough == 0) 147 | { 148 | result.push_back(b - total_len); 149 | } 150 | } 151 | lst.push_back(it); 152 | } 153 | else 154 | { 155 | for (auto it : lst) 156 | { 157 | it->second += 1; 158 | } 159 | lst.clear(); 160 | not_enough = word2count.size(); 161 | 162 | if (b + total_len > S.length()) 163 | { 164 | break; 165 | } 166 | } 167 | } 168 | } 169 | } 170 | } 171 | 172 | return result; 173 | } 174 | }; 175 | -------------------------------------------------------------------------------- /Sudoku Solver.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void solveSudoku(vector>& board) 5 | { 6 | vector> dotpos; 7 | for (size_t r = 0; r < 9; ++r) 8 | { 9 | for (size_t c = 0; c < 9; ++c) 10 | { 11 | if (board[r][c] == '.') 12 | { 13 | dotpos.push_back(make_pair(r, c)); 14 | } 15 | } 16 | } 17 | 18 | dfs(board, dotpos, 0); 19 | } 20 | 21 | bool dfs(vector>& board, vector>& dotpos, size_t index) 22 | { 23 | if (index == dotpos.size()) 24 | { 25 | return true; 26 | } 27 | 28 | size_t r = dotpos[index].first; 29 | size_t c = dotpos[index].second; 30 | 31 | for (board[r][c] = '1'; board[r][c] <= '9'; board[r][c] += 1) 32 | { 33 | bool valid = true; 34 | for (size_t i = 0; valid && i < 9; ++i) 35 | { 36 | if (i != r && board[i][c] == board[r][c] 37 | || i != c && board[r][i] == board[r][c] 38 | || i != r % 3 * 3 + c % 3 && board[r / 3 * 3 + i / 3][c / 3 * 3 + i % 3] == board[r][c]) 39 | { 40 | valid = false; 41 | break; 42 | } 43 | } 44 | if (valid && dfs(board, dotpos, index + 1)) 45 | { 46 | return true; 47 | } 48 | } 49 | 50 | return false; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /Sum Root to Leaf Numbers.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 | { 12 | public: 13 | int sumNumbers(TreeNode *root) 14 | { 15 | int sum = 0; 16 | 17 | vector> level; 18 | vector> next_level; 19 | 20 | if (root != nullptr) 21 | { 22 | level.push_back(make_pair(root, root->val)); 23 | } 24 | 25 | while (!level.empty()) 26 | { 27 | for (auto p : level) 28 | { 29 | if (p.first->left == nullptr && p.first->right == nullptr) 30 | { 31 | sum += p.second; 32 | } 33 | if (p.first->left != nullptr) 34 | { 35 | next_level.push_back(make_pair(p.first->left, p.second * 10 + p.first->left->val)); 36 | } 37 | if (p.first->right != nullptr) 38 | { 39 | next_level.push_back(make_pair(p.first->right, p.second * 10 + p.first->right->val)); 40 | } 41 | } 42 | level.swap(next_level); 43 | next_level.clear(); 44 | } 45 | 46 | return sum; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Surrounded Regions.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void solve(vector>& board) 5 | { 6 | if (board.empty() || board[0].empty()) 7 | { 8 | return ; 9 | } 10 | 11 | size_t rows = board.size(); 12 | size_t columns = board[0].size(); 13 | 14 | for (size_t c = 0; c < columns; ++c) 15 | { 16 | if (board[0][c] == 'O') 17 | { 18 | changeO2T(board, 0, c); 19 | } 20 | if (board[rows - 1][c] == 'O') 21 | { 22 | changeO2T(board, rows - 1, c); 23 | } 24 | } 25 | 26 | for (size_t r = 0; r < columns; ++r) 27 | { 28 | if (board[r][0] == 'O') 29 | { 30 | changeO2T(board, r, 0); 31 | } 32 | if (board[r][columns - 1] == 'O') 33 | { 34 | changeO2T(board, r, columns - 1); 35 | } 36 | } 37 | 38 | for (size_t r = 0; r < rows; ++r) 39 | { 40 | for (size_t c = 0; c < columns; ++c) 41 | { 42 | if (board[r][c] == 'O') 43 | { 44 | board[r][c] = 'X'; 45 | } 46 | } 47 | } 48 | 49 | for (size_t r = 0; r < rows; ++r) 50 | { 51 | for (size_t c = 0; c < columns; ++c) 52 | { 53 | if (board[r][c] == 'T') 54 | { 55 | board[r][c] = 'O'; 56 | } 57 | } 58 | } 59 | } 60 | 61 | void changeO2T(vector>& board, size_t row, size_t column) 62 | { 63 | board[row][column] = 'T'; 64 | 65 | if (row > 0 && board[row - 1][column] == 'O') 66 | { 67 | changeO2T(board, row - 1, column); 68 | } 69 | if (row + 1 < board.size() && board[row + 1][column] == 'O') 70 | { 71 | changeO2T(board, row + 1, column); 72 | } 73 | if (column > 0 && board[row][column - 1] == 'O') 74 | { 75 | changeO2T(board, row, column - 1); 76 | } 77 | if (column + 1 < board[0].size() && board[row][column + 1] == 'O') 78 | { 79 | changeO2T(board, row, column + 1); 80 | } 81 | } 82 | }; 83 | -------------------------------------------------------------------------------- /Swap Nodes in Pairs.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 | { 11 | public: 12 | ListNode *swapPairs(ListNode *head) 13 | { 14 | ListNode* cur = head; 15 | while (cur != NULL && cur->next != NULL) 16 | { 17 | swap(cur->val, cur->next->val); 18 | cur = cur->next->next; 19 | } 20 | return head; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Symmetric Tree.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 | { 12 | public: 13 | bool isSymmetric(TreeNode* a, TreeNode* b) 14 | { 15 | if (a != nullptr && b != nullptr) 16 | { 17 | return (a->val == b->val) 18 | && isSymmetric(a->left, b->right) 19 | && isSymmetric(a->right, b->left); 20 | } 21 | 22 | return (a == nullptr && b == nullptr); 23 | } 24 | 25 | bool isSymmetric(TreeNode* root) 26 | { 27 | return (root == nullptr) || isSymmetric(root->left, root->right); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Text Justification.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector fullJustify(vector& words, int L) 5 | { 6 | vector result; 7 | 8 | size_t begin = 0; 9 | size_t end = 0; 10 | while (end < words.size()) 11 | { 12 | size_t total = words[end].size(); 13 | end += 1; 14 | 15 | while (end < words.size() && total + (end - begin) + words[end].size() <= L) 16 | { 17 | total += words[end].size(); 18 | end += 1; 19 | } 20 | 21 | string line(words[begin]); 22 | size_t count = end - begin; 23 | if (end < words.size()) 24 | { 25 | if (count > 1) 26 | { 27 | size_t space = (L - total) / (count - 1); 28 | size_t m = (L - total) % (count - 1); 29 | for (size_t i = 1; i < count; ++i) 30 | { 31 | if (i <= m) 32 | { 33 | line.append(space + 1, ' '); 34 | } 35 | else 36 | { 37 | line.append(space, ' '); 38 | } 39 | line.append(words[begin + i]); 40 | }; 41 | } 42 | else 43 | { 44 | line.append(L - total, ' '); 45 | } 46 | } 47 | else 48 | { 49 | for (size_t i = begin + 1; i < end; ++i) 50 | { 51 | line.append(1, ' '); 52 | line.append(words[i]); 53 | } 54 | line.append(L - total - (count - 1), ' '); 55 | } 56 | result.push_back(line); 57 | 58 | begin = end; 59 | } 60 | 61 | return result; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int trap(int A[], int n) 5 | { 6 | int water = 0; 7 | 8 | if (n > 0) 9 | { 10 | int* left = new int[n]; 11 | int* right = new int[n]; 12 | 13 | left[0] = A[0]; 14 | int top = A[0]; 15 | for (int i = 1; i < n; ++i) 16 | { 17 | top = max(top, A[i]); 18 | left[i] = top; 19 | } 20 | 21 | right[n-1] = A[n-1]; 22 | top = A[n-1]; 23 | for (int i = n - 2; i >= 0; --i) 24 | { 25 | top = max(top, A[i]); 26 | right[i] = top; 27 | } 28 | 29 | for (int i = 0; i < n; ++i) 30 | { 31 | water += (min(left[i], right[i]) - A[i]); 32 | } 33 | 34 | delete[] left; 35 | delete[] right; 36 | } 37 | 38 | return water; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minimumTotal(vector > &triangle) 5 | { 6 | vector pathsum(triangle.size()); 7 | vector temp(triangle.size()); 8 | pathsum[0] = triangle[0][0]; 9 | for (size_t i = 1; i < triangle.size(); ++i) 10 | { 11 | pathsum.swap(temp); 12 | pathsum[0] = temp[0] + triangle[i][0]; 13 | pathsum[i] = temp[i-1] + triangle[i][i]; 14 | for (size_t j = 1; j < i; ++j) 15 | { 16 | pathsum[j] = triangle[i][j] + min(temp[j-1], temp[j]); 17 | } 18 | } 19 | return *min_element(pathsum.begin(), pathsum.end()); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Two Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector twoSum(vector& numbers, int target) 5 | { 6 | vector result; 7 | for (int i = 0; i < numbers.size(); ++i) 8 | { 9 | for (int j = i + 1; j < numbers.size(); ++j) 10 | { 11 | if (numbers[i] + numbers[j] == target) 12 | { 13 | result.push_back(i + 1); 14 | result.push_back(j + 1); 15 | return result; 16 | } 17 | } 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Unique Binary Search Trees II.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 | { 12 | public: 13 | vector generateTrees(int n) 14 | { 15 | vector trees; 16 | generateTrees(1, n + 1, trees); 17 | return trees; 18 | } 19 | 20 | void generateTrees(int begin, int end, vector& trees) 21 | { 22 | if (begin != end) 23 | { 24 | for (int n = begin; n < end; ++n) 25 | { 26 | vector left_trees; 27 | vector right_trees; 28 | generateTrees(begin, n, left_trees); 29 | generateTrees(n + 1, end, right_trees); 30 | for (auto left_root : left_trees) 31 | { 32 | for (auto right_root : right_trees) 33 | { 34 | TreeNode* root = new TreeNode(n); 35 | root->left = left_root; 36 | root->right = right_root; 37 | trees.push_back(root); 38 | } 39 | } 40 | } 41 | } 42 | else 43 | { 44 | trees.push_back(nullptr); 45 | } 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Unique Binary Search Trees.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int numTrees(int n) 5 | { 6 | int total[100] = {1}; 7 | for (int i = 1; i <= n; ++i) 8 | { 9 | total[i] = (total[(i - 1) / 2] * total[i / 2] * (2 - i % 2)); 10 | for (int j = 0; j < (i - 1) / 2; ++j) 11 | { 12 | total[i] += (total[j] * total[i - 1 - j] * 2); 13 | } 14 | } 15 | return total[n]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Unique Paths II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePathsWithObstacles(vector > &obstacleGrid) 4 | { 5 | const int row = obstacleGrid.size(); 6 | const int column = obstacleGrid[0].size(); 7 | 8 | vector path(obstacleGrid[0].size(), 1); 9 | if (obstacleGrid[0][0] == 1) 10 | { 11 | path[0] = 0; 12 | } 13 | for (size_t c = 1; c < column; ++c) 14 | { 15 | if (obstacleGrid[0][c] == 1 || path[c - 1] == 0) 16 | { 17 | path[c] = 0; 18 | } 19 | } 20 | 21 | for (size_t r = 1; r < row; ++r) 22 | { 23 | if (obstacleGrid[r][0] == 1) 24 | { 25 | path[0] = 0; 26 | } 27 | for (size_t c = 1; c < column; ++c) 28 | { 29 | if (obstacleGrid[r][c] == 1) 30 | { 31 | path[c] = 0; 32 | } 33 | else 34 | { 35 | path[c] += path[c - 1]; 36 | } 37 | } 38 | } 39 | 40 | return path.back(); 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int uniquePaths(int m, int n) 5 | { 6 | vector path(m, 1); 7 | for (size_t i = 1; i < n; ++i) 8 | { 9 | for (size_t j = 1; j < m; ++j) 10 | { 11 | path[j] += path[j - 1]; 12 | } 13 | } 14 | return path.back(); 15 | } 16 | }; 17 | 18 | class Solution2 19 | { 20 | public: 21 | int GCD(int m, int n) 22 | { 23 | if (m < n) 24 | { 25 | swap(m, n); 26 | } 27 | 28 | int r = m % n; 29 | while (r != 0) 30 | { 31 | m = n; 32 | n = r; 33 | r = m % n; 34 | } 35 | 36 | return n; 37 | } 38 | 39 | int uniquePaths(int m, int n) 40 | { 41 | m -= 1; 42 | n -= 1; 43 | 44 | int total = 1; 45 | for (int i = 0; i < min(m, n); ++i) 46 | { 47 | int gcd = GCD(m + n - i, i + 1); 48 | total /= ((i + 1) / gcd); 49 | total *= ((m + n - i) / gcd); 50 | } 51 | 52 | return total; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /Valid Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isNumber(const char *s) 5 | { 6 | enum InputType 7 | { 8 | INVALID, // 0 9 | SPACE, // 1 10 | SIGN, // 2 11 | DIGIT, // 3 12 | DOT, // 4 13 | EXPONENT, // 5 14 | NUM_INPUTS // 6 15 | }; 16 | 17 | int transitionTable[][NUM_INPUTS] = 18 | { 19 | -1, 0, 3, 1, 2, -1, // next states for state 0 20 | -1, 8, -1, 1, 4, 5, // next states for state 1 21 | -1, -1, -1, 4, -1, -1, // next states for state 2 22 | -1, -1, -1, 1, 2, -1, // next states for state 3 23 | -1, 8, -1, 4, -1, 5, // next states for state 4 24 | -1, -1, 6, 7, -1, -1, // next states for state 5 25 | -1, -1, -1, 7, -1, -1, // next states for state 6 26 | -1, 8, -1, 7, -1, -1, // next states for state 7 27 | -1, 8, -1, -1, -1, -1, // next states for state 8 28 | }; 29 | 30 | int state = 0; 31 | while (*s != '\0') 32 | { 33 | InputType inputType = INVALID; 34 | if (isspace(*s)) 35 | inputType = SPACE; 36 | else if (*s == '+' || *s == '-') 37 | inputType = SIGN; 38 | else if (isdigit(*s)) 39 | inputType = DIGIT; 40 | else if (*s == '.') 41 | inputType = DOT; 42 | else if (*s == 'e' || *s == 'E') 43 | inputType = EXPONENT; 44 | 45 | state = transitionTable[state][inputType]; 46 | 47 | if (state == -1) 48 | return false; 49 | else 50 | ++s; 51 | } 52 | 53 | return state == 1 || state == 4 || state == 7 || state == 8; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /Valid Palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isPalindrome(string s) 5 | { 6 | string alpha; 7 | for (auto it = s.begin(); it != s.end(); ++it) 8 | { 9 | if (isalnum(*it)) 10 | { 11 | alpha.push_back(tolower(*it)); 12 | } 13 | } 14 | string r(alpha); 15 | reverse(r.begin(), r.end()); 16 | return alpha == r; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isValid(string s) 5 | { 6 | stack cc; 7 | for (size_t i = 0; i < s.length(); ++i) 8 | { 9 | if (s[i] == '(' || s[i] == '[' || s[i] == '{') 10 | { 11 | cc.push(s[i]); 12 | } 13 | else 14 | { 15 | if (!cc.empty() && (s[i] == ')' && cc.top() == '(' || s[i] == ']' && cc.top() == '[' || s[i] == '}' && cc.top() == '{')) 16 | { 17 | cc.pop(); 18 | } 19 | else 20 | { 21 | return false; 22 | } 23 | } 24 | } 25 | 26 | return cc.empty(); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Valid Sudoku.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isValidSudoku(vector > &board) 5 | { 6 | bool rows[9][9] = {false}; 7 | bool cols[9][9] = {false}; 8 | bool blocks[9][9] = {false}; 9 | 10 | for (size_t r = 0; r < 9; ++r) 11 | { 12 | for (int c = 0; c < 9; ++c) 13 | { 14 | if (board[r][c] == '.') 15 | { 16 | continue; 17 | } 18 | 19 | int n = board[r][c] - '1'; 20 | if (rows[r][n] || cols[c][n] || blocks[r / 3 * 3 + c / 3][n]) 21 | { 22 | return false; 23 | } 24 | 25 | rows[r][n] = true; 26 | cols[c][n] = true; 27 | blocks[r / 3 * 3 + c / 3][n] = true; 28 | } 29 | } 30 | 31 | return true; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Validate Binary Search Tree.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 | { 12 | public: 13 | bool isValidBST(TreeNode *root) 14 | { 15 | vector vals; 16 | TreeNode* cur = root; 17 | while (cur != nullptr) 18 | { 19 | if (cur->left == nullptr) 20 | { 21 | vals.push_back(cur->val); 22 | cur = cur->right; 23 | } 24 | else 25 | { 26 | TreeNode* temp = cur->left; 27 | while (temp->right != nullptr && temp->right != cur) 28 | { 29 | temp = temp->right; 30 | } 31 | if (temp->right == nullptr) 32 | { 33 | temp->right = cur; 34 | cur = cur->left; 35 | } 36 | else 37 | { 38 | vals.push_back(cur->val); 39 | temp->right = nullptr; 40 | cur = cur->right; 41 | } 42 | } 43 | } 44 | 45 | bool valid = true; 46 | for (size_t i = 1; i < vals.size(); ++i) 47 | { 48 | if (vals[i-1] >= vals[i]) 49 | { 50 | valid = false; 51 | break; 52 | } 53 | } 54 | return valid; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Wildcard Matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isMatch(const char *s, const char *p) 5 | { 6 | if(!s && !p) return true; 7 | 8 | const char *star_p=NULL, *star_s=NULL; 9 | 10 | while(*s) 11 | { 12 | if(*p == '?' || *p == *s) 13 | { 14 | ++p,++s; 15 | } 16 | else if(*p == '*') 17 | { 18 | while(*p == '*') 19 | { 20 | ++p; 21 | } 22 | 23 | if(!*p) return true; 24 | 25 | star_p = p; 26 | star_s = s; 27 | } 28 | else if ((!*p || *p != *s) && star_p) 29 | { 30 | s = ++star_s; 31 | p = star_p; 32 | } 33 | else 34 | { 35 | return false; 36 | } 37 | } 38 | 39 | while (*p) 40 | { 41 | if(*p++ != '*') 42 | { 43 | return false; 44 | } 45 | } 46 | 47 | return true; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Word Ladder II.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void search_next_reach(unordered_set& reach, const unordered_set& other_reach, unordered_set& meet, unordered_map>& path, unordered_set& dict) 5 | { 6 | unordered_set temp; 7 | reach.swap(temp); 8 | 9 | for (auto it = temp.begin(); it != temp.end(); ++it) 10 | { 11 | string s = *it; 12 | for (size_t i = 0; i < s.length(); ++i) 13 | { 14 | char back = s[i]; 15 | for (s[i] = 'a'; s[i] <= 'z'; ++s[i]) 16 | { 17 | if (s[i] != back) 18 | { 19 | if (reach.count(s) == 1) 20 | { 21 | path[s].push_back(*it); 22 | } 23 | else if (dict.erase(s) == 1) 24 | { 25 | path[s].push_back(*it); 26 | reach.insert(s); 27 | } 28 | else if (other_reach.count(s) == 1) 29 | { 30 | path[s].push_back(*it); 31 | reach.insert(s); 32 | meet.insert(s); 33 | } 34 | } 35 | } 36 | s[i] = back; 37 | } 38 | } 39 | } 40 | 41 | void walk(vector>& all_path, unordered_map> kids) 42 | { 43 | vector> temp; 44 | while (!kids[all_path.back().back()].empty()) 45 | { 46 | all_path.swap(temp); 47 | all_path.clear(); 48 | for (auto it = temp.begin(); it != temp.end(); ++it) 49 | { 50 | vector& one_path = *it; 51 | vector& p = kids[one_path.back()]; 52 | for (size_t i = 0; i < p.size(); ++i) 53 | { 54 | all_path.push_back(one_path); 55 | all_path.back().push_back(p[i]); 56 | } 57 | } 58 | } 59 | } 60 | 61 | vector> findLadders(string start, string end, unordered_set& dict) 62 | { 63 | vector> result, result_temp; 64 | if (dict.erase(start) == 1 && dict.erase(end) == 1) 65 | { 66 | unordered_map> kids_from_start; 67 | unordered_map> kids_from_end; 68 | 69 | unordered_set reach_start({start}); 70 | unordered_set reach_end({end}); 71 | 72 | unordered_set meet; 73 | while (meet.empty() && !reach_start.empty() && !reach_end.empty()) 74 | { 75 | if (reach_start.size() < reach_end.size()) 76 | { 77 | search_next_reach(reach_start, reach_end, meet, kids_from_start, dict); 78 | } 79 | else 80 | { 81 | search_next_reach(reach_end, reach_start, meet, kids_from_end, dict); 82 | } 83 | } 84 | 85 | if (!meet.empty()) 86 | { 87 | for (auto it = meet.begin(); it != meet.end(); ++it) 88 | { 89 | result.push_back({*it}); 90 | } 91 | 92 | walk(result, kids_from_start); 93 | for (size_t i = 0; i < result.size(); ++i) 94 | { 95 | reverse(result[i].begin(), result[i].end()); 96 | } 97 | walk(result, kids_from_end); 98 | } 99 | } 100 | 101 | return result; 102 | } 103 | }; 104 | -------------------------------------------------------------------------------- /Word Ladder.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int ladderLength(string start, string end, unordered_set &dict) 5 | { 6 | if (dict.count(start) && dict.count(end)) 7 | { 8 | if (start == end) 9 | return 1; 10 | 11 | vector reach({start}), temp; 12 | int step = 1; 13 | while (!reach.empty()) 14 | { 15 | step += 1; 16 | for (auto it = reach.begin(); it != reach.end(); ++it) 17 | { 18 | string& s = *it; 19 | for (size_t i = 0; i < s.length(); ++i) 20 | { 21 | char back = s[i]; 22 | for (s[i] = 'a'; s[i] <= 'z'; ++s[i]) 23 | if (s[i] != back && dict.erase(s) == 1) 24 | { 25 | if (s == end) 26 | return step; 27 | temp.push_back(s); 28 | } 29 | s[i] = back; 30 | } 31 | } 32 | reach.swap(temp); 33 | temp.clear(); 34 | } 35 | } 36 | return 0; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Word Search.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool exist(vector>& board, string word) 5 | { 6 | rows = board.size(); 7 | cols = board[0].size(); 8 | 9 | if (rows * cols < word.size()) 10 | return false; 11 | 12 | for (size_t r = 0; r < rows; ++r) 13 | for (size_t c = 0; c < cols; ++c) 14 | if (board[r][c] == word[0]) 15 | if (dfs(board, r, c, word, 1)) 16 | return true; 17 | 18 | return false; 19 | } 20 | 21 | bool dfs(vector>& board, size_t row, size_t col, string& word, size_t pos) 22 | { 23 | if (pos == word.size()) 24 | return true; 25 | 26 | board[row][col] = 0; 27 | if (row > 0 && board[row - 1][col] == word[pos] && dfs(board, row - 1, col, word, pos + 1) 28 | || col > 0 && board[row][col - 1] == word[pos] && dfs(board, row, col - 1, word, pos + 1) 29 | || row + 1 < rows && board[row + 1][col] == word[pos] && dfs(board, row + 1, col, word, pos + 1) 30 | || col + 1 < cols && board[row][col + 1] == word[pos] && dfs(board, row, col + 1, word, pos + 1)) 31 | { 32 | return true; 33 | } 34 | board[row][col] = word[pos - 1]; 35 | 36 | return false; 37 | } 38 | 39 | private: 40 | size_t rows; 41 | size_t cols; 42 | }; 43 | -------------------------------------------------------------------------------- /ZigZag Conversion.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string convert(string s, int nRows) 5 | { 6 | if (nRows == 1) 7 | { 8 | return s; 9 | } 10 | 11 | string result; 12 | int cycle = nRows * 2 - 2; 13 | for (int i = 0; i < s.length(); i += cycle) 14 | { 15 | result.push_back(s[i]); 16 | } 17 | 18 | int rounds = s.length() / cycle; 19 | for (int row = 1; row < nRows - 1; ++row) 20 | { 21 | int start = 0; 22 | while (start < s.length()) 23 | { 24 | if (start + row < s.length()) 25 | { 26 | result.push_back(s[start + row]); 27 | } 28 | if (start + cycle - row < s.length()) 29 | { 30 | result.push_back(s[start + cycle - row]); 31 | } 32 | 33 | start += cycle; 34 | } 35 | } 36 | 37 | for (int i = nRows - 1; i < s.length(); i += cycle) 38 | { 39 | result.push_back(s[i]); 40 | } 41 | 42 | return result; 43 | } 44 | }; 45 | --------------------------------------------------------------------------------