├── README.md ├── code ├── 0001. TwoSum.h ├── 0002. AddTwoNumbers.h ├── 0003LongestSubstrWithoutRepeatingCharacters.h ├── 0004. Median of Two Sorted Arrays.h ├── 0005LongestPalindromicSubstr.h ├── 0006. ZigZag Conversion.h ├── 0007. Reverse Integer.h ├── 0009. Palindrome Number.h ├── 0010. Regular Expression Matching.h ├── 0011. Container With Most Water.h ├── 0012. Integer to Roman.h ├── 0013. Roman to Integer.h ├── 0014. Longest Common Prefix.h ├── 0015. 3Sum.h ├── 0016. 3Sum Closest.h ├── 0017. Letter Combinations of a Phone Number.h ├── 0018. 4Sum.h ├── 0019. Remove Nth Node From End of List.h ├── 0020. Valid Parentheses.h ├── 0021. Merge Two Sorted Lists.h ├── 0022. Generate Parentheses.h ├── 0023. Merge k Sorted Lists.h ├── 0029. Divide Two Integers.h ├── 0030. Substring with Concatenation of All Words.h ├── 0037. Sudoku Solver ├── 0039Combination Sum.h ├── 0040Combination Sum II.h ├── 0043. Multiply Strings.h ├── 0044Wildcard Matching.h ├── 0045. Jump Game II.h ├── 0046. Permutations.h ├── 0047. Permutations II.h ├── 0051. N-Queens.h ├── 0052. N-Queens II.h ├── 0055. Jump Game.h ├── 0060. Permutation Sequence.h ├── 0069. Sqrt(x).h ├── 0072Edit Distance.h ├── 0076. Minimum Window Substring.h ├── 0077. Combinations.h ├── 0078. Subsets.h ├── 0079. Word Search.h ├── 0084. Largest Rectangle in Histogram.h ├── 0085. Maximal Rectangle.h ├── 0087. Scramble String.h ├── 0088. Merge Sorted Array.h ├── 0090. Subsets II.h ├── 0091. Decode Ways.h ├── 0094. Binary Tree Inorder Traversal.h ├── 0096Unique Binary Search Trees.h ├── 0097. Interleaving String.h ├── 0098. Validate Binary Search Tree.h ├── 0099. Recover Binary Search Tree.h ├── 0107. Binary Tree Level Order Traversal II.h ├── 0110. Balanced Binary Tree.h ├── 0113. Path Sum II.h ├── 0115. Distinct Subsequences.h ├── 0116. Populating Next Right Pointers in Each Node.h ├── 0123. Best Time to Buy and Sell Stock III.h ├── 0124. Binary Tree Maximum Path Sum.h ├── 0126. Word Ladder II.h ├── 0128. Longest Consecutive Sequence.h ├── 0131. Palindrome Partitioning.h ├── 0132. Palindrome Partitioning II.h ├── 0134. Gas Station.h ├── 0136. Single Number.h ├── 0137. Single Number II.h ├── 0139. Word Break.h ├── 0140. Word Break II.h ├── 0143. Reorder List.h ├── 0144. Binary Tree Preorder Traversal.h ├── 0145. Binary Tree Postorder Traversal.h ├── 0149. Max Points on a Line.h ├── 0151. Reverse Words in a String.h ├── 0153. Find Minimum in Rotated Sorted Array.h ├── 0154. Find Minimum in Rotated Sorted Array II.h ├── 0157. Read N Characters Given Read4.h ├── 0158. Read N Characters Given Read4 II - Call multiple times.h ├── 0166. Fraction to Recurring Decimal.h ├── 0173. Binary Search Tree Iterator.h ├── 0174Dungeon Game.h ├── 0188. Best Time to Buy and Sell Stock IV.h ├── 0190. Reverse Bits.h ├── 0198House Robber.h ├── 0207. Course Schedule ├── 0208. Implement Trie (Prefix Tree).h ├── 0210. Course Schedule II.h ├── 0211. Add and Search Word - Data structure design.h ├── 0212. Word Search II.h ├── 0213House Robber II.h ├── 0216. Combination Sum III.h ├── 0218. The Skyline Problem.h ├── 0221. Maximal Square.h ├── 0223. Rectangle Area.h ├── 0224. Basic Calculator.h ├── 0227. Basic Calculator II.h ├── 0230. Kth Smallest Element in a BST.h ├── 0231. Power of Two.h ├── 0234. Palindrome Linked List.h ├── 0235. Lowest Common Ancestor of a Binary Search Tree.h ├── 0236. Lowest Common Ancestor of a Binary Tree.h ├── 0236Lowest Common Ancestor of a Binary Tree.h ├── 0239. Sliding Window Maximum.h ├── 0241. Different Ways to Add Parentheses.h ├── 0251. Flatten 2D Vector.h ├── 0256Paint House.h ├── 0257. Binary Tree Paths.h ├── 0260. Single Number III.h ├── 0261. Graph Valid Tree.h ├── 0265Paint House II.h ├── 0268. Missing Number.h ├── 0269. Alien Dictionary.h ├── 0271. Encode and Decode Strings.h ├── 0273. Integer to English Words.h ├── 0275H-Index II.h ├── 0276Paint Fence.h ├── 0277. Find the Celebrity.h ├── 0278First Bad Version.h ├── 0279Perfect Squares.h ├── 0282. Expression Add Operators.h ├── 0285. Inorder Successor in BST.h ├── 0286. Walls and Gates.h ├── 0291. Word Pattern II.h ├── 0295. Find Median from Data Stream.h ├── 0297. Serialize and Deserialize Binary Tree.h ├── 0300. Longest Increasing Subsequence.h ├── 0301. Remove Invalid Parentheses.h ├── 0304. Range Sum Query 2D - Immutable.h ├── 0307. Range Sum Query - Mutable.h ├── 0308. Range Sum Query 2D - Mutable.h ├── 0309. Best Time to Buy and Sell Stock with Cooldown.h ├── 0310. Minimum Height Trees.h ├── 0311. Sparse Matrix Multiplication.h ├── 0312Burst Balloons.h ├── 0314. Binary Tree Vertical Order Traversal.h ├── 0315. Count of Smaller Numbers After Self.h ├── 0322. Coin Change.h ├── 0327. Count of Range Sum.h ├── 0329. Longest Increasing Path in a Matrix.h ├── 0332. Reconstruct Itinerary.h ├── 0336. Palindrome Pairs.h ├── 0337. House Robber III.h ├── 0338Counting Bits.h ├── 0340. Longest Substring with At Most K Distinct Characters.h ├── 0342. Power of Four.h ├── 0343. Integer Break.h ├── 0348. Design Tic-Tac-Toe.h ├── 0351. Android Unlock Patterns.h ├── 0354. Russian Doll Envelopes.h ├── 0358. Rearrange String k Distance Apart.h ├── 0361. Bomb Enemy.h ├── 0362. Design Hit Counter.h ├── 0363. Max Sum of Rectangle No Larger Than K.h ├── 0368. Largest Divisible Subset.h ├── 0371. Sum of Two Integers.h ├── 0374Guess Number Higher or Lower.h ├── 0377. Combination Sum IV.h ├── 0378Kth Smallest Element in a Sorted Matrix.h ├── 0382. Linked List Random Node.h ├── 0395. Longest Substring with At Least K Repeating Characters.h ├── 0399. Evaluate Division.h ├── 0401. Binary Watch.h ├── 0402. Remove K Digits.h ├── 0410. Split Array Largest Sum.h ├── 0416. Partition Equal Subset Sum.h ├── 0426. Convert Binary Search Tree to Sorted Doubly Linked List.h ├── 0428. Serialize and Deserialize N-ary Tree.h ├── 0429. N-ary Tree Level Order Traversal.h ├── 0435. Non-overlapping Intervals.h ├── 0437. Path Sum III.h ├── 0441Arranging Coins.h ├── 0443. String Compression.h ├── 0444. Sequence Reconstruction.h ├── 0450. Delete Node in a BST.h ├── 0452. Minimum Number of Arrows to Burst Balloons.h ├── 0459. Repeated Substring Pattern.h ├── 0477. Total Hamming Distance.h ├── 0487. Max Consecutive Ones II.h ├── 0489. Robot Room Cleaner.h ├── 0490. The Maze.h ├── 0491. Increasing Subsequences.h ├── 0493. Reverse Pairs.h ├── 0494. Target Sum.h ├── 0498. Diagonal Traverse.h ├── 0499. The Maze III.h ├── 0501. Find Mode in Binary Search Tree.h ├── 0503. Next Greater Element II.h ├── 0505. The Maze II.h ├── 0516Longest Palindromic Subsequence.h ├── 0518. Coin Change 2.h ├── 0525. Contiguous Array.h ├── 0535. Encode and Decode TinyURL.h ├── 0540. Single Element in a Sorted Array.h ├── 0542. 01 Matrix.h ├── 0546. Remove Boxes ├── 0547. Friend Circles.h ├── 0548. Split Array with Equal Sum.h ├── 0560. Subarray Sum Equals K.h ├── 0572. Subtree of Another Tree.h ├── 0576. Out of Boundary Paths.h ├── 0583Delete Operation for Two Strings.h ├── 0590. N-ary Tree Postorder Traversal.h ├── 0616. Add Bold Tag in String.h ├── 0630. Course Schedule III.h ├── 0634. Find the Derangement of An Array.h ├── 0638. Shopping Offers.h ├── 0639. Decode Ways II.h ├── 0650_2 Keys Keyboard.h ├── 0651_4 Keys Keyboard.h ├── 0656. Coin Path.h ├── 0658. Find K Closest Elements.h ├── 0662. Maximum Width of Binary Tree.h ├── 0673. Number of Longest Increasing Subsequence.h ├── 0678. Valid Parenthesis String.h ├── 0684. Redundant Connection.h ├── 0685. Redundant Connection II.h ├── 0687. Longest Univalue Path.h ├── 0688. Knight Probability in Chessboard.h ├── 0691. Stickers to Spell Word.h ├── 0698. Partition to K Equal Sum Subsets.h ├── 0701. Insert into a Binary Search Tree.h ├── 0704Binary Search.h ├── 0712Minimum ASCII Delete Sum for Two Strings.h ├── 0715. Range Module.h ├── 0716. Max Stack.h ├── 0718Maximum Length of Repeated Subarray.h ├── 0720. Longest Word in Dictionary.h ├── 0721. Accounts Merge.h ├── 0723. Candy Crush.h ├── 0726. Number of Atoms.h ├── 0727. Minimum Window Subsequence.h ├── 0737. Sentence Similarity II.h ├── 0739. Daily Temperatures.h ├── 0740. Delete and Earn.h ├── 0741. Cherry Pickup.h ├── 0743. Network Delay Time.h ├── 0745. Prefix and Suffix Search.h ├── 0752. Open the Lock.h ├── 0756. Pyramid Transition Matrix.h ├── 0768. Max Chunks To Make Sorted II.h ├── 0769. Max Chunks To Make Sorted.h ├── 0772. Basic Calculator III.h ├── 0773. Sliding Puzzle.h ├── 0774. Minimize Max Distance to Gas Station.h ├── 0783. Minimum Distance Between BST Nodes.h ├── 0785. Is Graph Bipartite.h ├── 0787. Cheapest Flights Within K Stops.h ├── 0790. Domino and Tromino Tiling.h ├── 0792. Number of Matching Subsequences.h ├── 0801Minimum Swaps To Make Sequences Increasing.h ├── 0802. Find Eventual Safe States.h ├── 0809. Expressive Words.h ├── 0813. Largest Sum of Averages.h ├── 0814. Binary Tree Pruning.h ├── 0815. Bus Routes.h ├── 0818. Race Car.h ├── 0824. Goat Latin.h ├── 0825. Friends Of Appropriate Ages.h ├── 0827. Making A Large Island.h ├── 0836. Rectangle Overlap ├── 0850. Rectangle Area II.h ├── 0857. Minimum Cost to Hire K Workers.h ├── 0862. Shortest Subarray with Sum at Least K.h ├── 0863. All Nodes Distance K in Binary Tree.h ├── 0872. Leaf-Similar Trees.h ├── 0875Koko Eating Bananas.h ├── 0877. Stone Game.h ├── 0886. Possible Bipartition.h ├── 0889. Construct Binary Tree from Preorder and Postorder Traversal.h ├── 0894. All Possible Full Binary Trees.h ├── 0897. Increasing Order Search Tree.h ├── 0901. Online Stock Span.h ├── 0907. Sum of Subarray Minimums.h ├── 0909. Snakes and Ladders.h ├── 0911. Online Election.h ├── 0918. Maximum Sum Circular Subarray.h ├── 0921. Minimum Add to Make Parentheses Valid.h ├── 0935. Knight Dialer.h ├── 0947. Most Stones Removed with Same Row or Column.h ├── 0952. Largest Component Size by Common Factor.h ├── 0955. Delete Columns to Make Sorted II.h ├── 0959. Regions Cut By Slashes.h ├── 0962. Maximum Width Ramp.h ├── 0968. Binary Tree Cameras.h ├── 0969. Pancake Sorting.h ├── 0974. Subarray Sums Divisible by K.h ├── 0975. Odd Even Jump.h ├── 0979. Distribute Coins in Binary Tree.h ├── 0981. Time Based Key-Value Store.h ├── 0986. Interval List Intersections.h ├── 0987. Vertical Order Traversal of a Binary Tree.h ├── 0990. Satisfiability of Equality Equations.h ├── 0996. Number of Squareful Arrays.h ├── 0997. Find the Town Judge.h ├── 1004. Max Consecutive Ones III.h ├── 1008. Construct Binary Search Tree from Preorder Traversal ├── 1011. Capacity To Ship Packages Within D Days.h ├── 1013. Partition Array Into Three Parts With Equal Sum.h ├── 1016. Binary String With Substrings Representing 1 To N.h ├── 1017. Convert to Base -2.h ├── 1023. Camelcase Matching ├── 1024. Video Stitching.h ├── 1027. Longest Arithmetic Sequence.h ├── 1028. Recover a Tree From Preorder Traversal.h ├── 1029. Two City Scheduling.h ├── 1032. Stream of Characters.h ├── 1034. Coloring A Border.h ├── 1035. Uncrossed Lines.h ├── 1040. Moving Stones Until Consecutive II.h ├── 1042. Flower Planting With No Adjacent.h ├── 1043. Partition Array for Maximum Sum.h ├── 1046. Last Stone Weight.h ├── 1047. Remove All Adjacent Duplicates In String.h ├── 1048. Longest String Chain.h ├── 1049. Last Stone Weight II.h ├── 1052. Grumpy Bookstore Owner.h ├── 1054. Distant Barcodes.h ├── 1055. Shortest Way to Form String.h ├── 1057. Campus Bikes.h ├── 1058. Minimize Rounding Error to Meet Target.h ├── 1060. Missing Element in Sorted Array.h ├── 1061. Lexicographically Smallest Equivalent String.h ├── 1062. Longest Repeating Substring.h ├── 1063. Number of Valid Subarrays.h ├── 1065. Index Pairs of a String.h ├── 1066. Campus Bikes II.h ├── 1071. Greatest Common Divisor of Strings.h ├── 1072. Flip Columns For Maximum Number of Equal Rows.h ├── 1073. Adding Two Negabinary Numbers.h ├── 1074. Number of Submatrices That Sum to Target.h ├── 1080. Insufficient Nodes in Root to Leaf Paths.h ├── 1087. Brace Expansion.h ├── 1092. Shortest Common Supersequence.h ├── 1100. Find K-Length Substrings With No Repeated Characters.h ├── 1102. Path With Maximum Minimum Value.h ├── 1105. Filling Bookcase Shelves.h ├── 1109. Corporate Flight Bookings.h ├── 1110. Delete Nodes And Return Forest.h ├── 1111. Maximum Nesting Depth of Two Valid Parentheses Strings.h ├── 1123. Lowest Common Ancestor of Deepest Leaves.h ├── 1124. Longest Well-Performing Interval.h ├── 1125. Smallest Sufficient Team.h ├── 1130. Minimum Cost Tree From Leaf Values.h ├── 1135. Connecting Cities With Minimum Cost.h ├── 1139. Largest 1-Bordered Square.h ├── 1140. Stone Game II.h ├── 1146. Snapshot Array.h ├── 1152. Analyze User Website Visit Pattern.h ├── 1153. String Transforms Into Another String.h ├── 1155. Number of Dice Rolls With Target Sum.h ├── 1177. Can Make Palindrome from Substring.h ├── 1178. Number of Valid Words for Each Puzzle.h ├── 1187. Make Array Strictly Increasing.h ├── 1190. Reverse Substrings Between Each Pair of Parentheses.h ├── 1199. Minimum Time to Build Blocks.h └── 1230. Toss Strange Coins.h └── template ├── 2D_DP1.cpp ├── BFS.cpp ├── BackTracking1.cpp ├── BackTracking2.cpp ├── BinarySearch1.cpp ├── BinarySearch2.cpp ├── DFS.cpp ├── Dijkstra.cpp ├── SlidingWindow1.cpp └── UnionFind.cpp /code/0001. TwoSum.h: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 4 | 5 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 6 | 7 | Example: 8 | 9 | Given nums = [2, 7, 11, 15], target = 9, 10 | 11 | Because nums[0] + nums[1] = 2 + 7 = 9, 12 | return [0, 1]. 13 | */ 14 | 15 | class Solution { 16 | public: 17 | vector twoSum(vector& nums, int target) 18 | { 19 | //use hash map, val->pos 20 | //T O(N) M O(N) 21 | unordered_map hash; 22 | vector result; 23 | for(int i=0;i m; 22 | int start=0,res=0; 23 | for(int i=0;imax_len/2; ) 24 | { 25 | int start=i,end=i; //起始点 26 | while(end0 && s[end+1]==s[start-1]) 30 | { 31 | start--;end++; //expand 32 | } 33 | int new_len=end-start+1; 34 | if(new_len>max_len) 35 | { 36 | min_start=start; 37 | max_len=new_len; 38 | } 39 | } 40 | 41 | return s.substr(min_start,max_len); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /code/0006. ZigZag Conversion.h: -------------------------------------------------------------------------------- 1 | /* 2 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: 3 | (you may want to display this pattern in a fixed font for better legibility) 4 | P A H N 5 | A P L S I I G 6 | Y I R 7 | And then read line by line: "PAHNAPLSIIGYIR" 8 | Write the code that will take a string and make this conversion given a number of rows: 9 | 10 | string convert(string s, int numRows); 11 | 12 | Input: s = "PAYPALISHIRING", numRows = 3 13 | Output: "PAHNAPLSIIGYIR" 14 | 15 | Input: s = "PAYPALISHIRING", numRows = 4 16 | Output: "PINALSIGYAHRPI" 17 | Explanation: 18 | 19 | P I N 20 | A L S I G 21 | Y A H R 22 | P I 23 | */ 24 | 25 | string convert(string s, int numRows) { 26 | string result; 27 | int n=s.size(); 28 | if(numRows==1 || n<=numRows) return s; 29 | int new_p=numRows*2-2; 30 | for(int i=0;iINT_MAX/10) return 0; 22 | result=result*10+x%10; 23 | x/=10; 24 | } 25 | return result; 26 | } 27 | -------------------------------------------------------------------------------- /code/0011. Container With Most Water.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). 3 | n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, 4 | which together with x-axis forms a container, such that the container contains the most water. 5 | Note: You may not slant the container and n is at least 2. 6 | 7 | The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, 8 | the max area of water (blue section) the container can contain is 49. 9 | 10 | Input: [1,8,6,2,5,4,8,3,7] 11 | Output: 49 12 | */ 13 | 14 | int maxArea(vector& height) { 15 | //greedy 16 | //move short line can higher in height although lower in width 17 | int n=height.size(); 18 | if(n<=1) return 0; 19 | int i=0,j=n-1; 20 | int res=0; 21 | while(iheight[j]) 24 | j--; 25 | else 26 | i++; 27 | } 28 | return res; 29 | } 30 | -------------------------------------------------------------------------------- /code/0014. Longest Common Prefix.h: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | If there is no common prefix, return an empty string "". 4 | 5 | Input: ["flower","flow","flight"] 6 | Output: "fl" 7 | 8 | Input: ["dog","racecar","car"] 9 | Output: "" 10 | 11 | All given inputs are in lowercase letters a-z. 12 | */ 13 | 14 | string longestCommonPrefix(vector& strs) { 15 | if(strs.size()==0) 16 | return ""; 17 | int max=0; 18 | string s=""; 19 | while(true){ 20 | if(max> threeSum(vector& nums) { 17 | vector> result; 18 | int n=nums.size(); 19 | if (n<3) 20 | return result; 21 | sort(nums.begin(),nums.end()); 22 | 23 | for (int i=0;i0 && nums[i]==nums[i-1]) continue; 26 | 27 | int target=0-nums[i], start=i+1, end=n-1; 28 | while(starttarget) 32 | end--; 33 | else{ 34 | result.push_back({nums[i],nums[start],nums[end]}); 35 | //重复去掉 36 | while(start+1& nums, int target) { 10 | int result; 11 | int closest=INT_MAX; //record gap 12 | int n=nums.size(); 13 | if (n<3) 14 | return result; 15 | sort(nums.begin(),nums.end()); 16 | 17 | for (int i=0;i0 && nums[i]==nums[i-1]) continue; 20 | 21 | int goal=target-nums[i],start=i+1,end=n-1,gap; 22 | while(startgoal) 31 | end--; 32 | else 33 | return target; 34 | } 35 | 36 | } 37 | return result; 38 | } 39 | -------------------------------------------------------------------------------- /code/0017. Letter Combinations of a Phone Number.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. 3 | m['2']={'a','b','c'};m['3']={'d','e','f'};m['4']={'g','h','i'}; 4 | m['5']={'j','k','l'};m['6']={'m','n','o'};m['7']={'p','q','r','s'}; 5 | m['8']={'t','u','v'};m['9']={'w','x','y','z'}; 6 | */ 7 | 8 | void backtrack(vector &res,string &path, unordered_map> & m, string &digits,int pos, int n){ 9 | if(pos==n){ 10 | res.push_back(path); 11 | return; 12 | } 13 | for(int i=0;i letterCombinations(string digits) { 21 | //backtracking all solution 22 | vector res; 23 | if(digits=="") return res; 24 | unordered_map> m; 25 | m['2']={'a','b','c'};m['3']={'d','e','f'};m['4']={'g','h','i'}; 26 | m['5']={'j','k','l'};m['6']={'m','n','o'};m['7']={'p','q','r','s'}; 27 | m['8']={'t','u','v'};m['9']={'w','x','y','z'}; 28 | 29 | string path=""; 30 | backtrack(res,path,m,digits,0,digits.size()); 31 | return res; 32 | } 33 | -------------------------------------------------------------------------------- /code/0019. Remove Nth Node From End of List.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, remove the n-th node from the end of list and return its head. 3 | 4 | Example: 5 | 6 | Given linked list: 1->2->3->4->5, and n = 2. 7 | 8 | After removing the second node from the end, the linked list becomes 1->2->3->5. 9 | Note: 10 | 11 | Given n will always be valid. 12 | 13 | Follow up: 14 | Could you do this in one pass? 15 | */ 16 | 17 | ListNode* removeNthFromEnd(ListNode* head, int n) { 18 | ListNode dummy(0); 19 | dummy.next=head; 20 | ListNode* first=&dummy; 21 | for(int i=0;inext; 23 | ListNode* second=&dummy; 24 | while(first->next!=NULL){ 25 | first=first->next; 26 | second=second->next; 27 | } 28 | second->next=second->next->next; 29 | return dummy.next; 30 | } 31 | -------------------------------------------------------------------------------- /code/0021. Merge Two Sorted Lists.h: -------------------------------------------------------------------------------- 1 | /* 2 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 3 | 4 | Input: 1->2->4, 1->3->4 5 | Output: 1->1->2->3->4->4 6 | */ 7 | 8 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 9 | { 10 | ListNode dummy(INT_MIN); 11 | ListNode *p=&dummy; 12 | while(l1!=NULL && l2!=NULL) 13 | { 14 | if(l1->valval) 15 | { 16 | p->next=l1; 17 | l1=l1->next; 18 | } 19 | else 20 | { 21 | p->next=l2; 22 | l2=l2->next; 23 | } 24 | p=p->next; 25 | } 26 | if(l1!=NULL) p->next=l1; 27 | if(l2!=NULL) p->next=l2; 28 | return dummy.next; 29 | } 30 | -------------------------------------------------------------------------------- /code/0022. Generate Parentheses.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | 4 | For example, given n = 3, a solution set is: 5 | [ 6 | "((()))", 7 | "(()())", 8 | "(())()", 9 | "()(())", 10 | "()()()" 11 | ] 12 | */ 13 | 14 | //backtrack 15 | class Solution { 16 | public: 17 | void backtrack(vector &res, string &path, int left, int right, int total){ 18 | if(left+right==total){ 19 | res.push_back(path); 20 | return; 21 | } 22 | if(left>right){ 23 | path+=')'; 24 | backtrack(res,path,left,right+1,total); 25 | path.pop_back(); 26 | } 27 | if(left generateParenthesis(int n) { 35 | vector res; 36 | string path=""; 37 | backtrack(res,path,0,0,2*n); 38 | return res; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /code/0029. Divide Two Integers.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. 3 | Return the quotient after dividing dividend by divisor. 4 | 5 | The integer division should truncate toward zero. 6 | 7 | 8 | Input: dividend = 10, divisor = 3 9 | Output: 3 10 | 11 | Input: dividend = 7, divisor = -3 12 | Output: -2 13 | 14 | Note: 15 | Both dividend and divisor will be 32-bit signed integers. 16 | The divisor will never be 0. 17 | Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. 18 | For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows. 19 | */ 20 | 21 | int divide(int A, int B) { 22 | //Int_min/-1 23 | if (A == INT_MIN && B == -1) return INT_MAX; 24 | 25 | long a = abs((long)A), b = abs((long)B), res = 0; 26 | for(int i=31;i>=0;i--){ 27 | if( (a>>i) >= b){ 28 | res+=(1< 0) == (B > 0) ? res : -res; 33 | } 34 | -------------------------------------------------------------------------------- /code/0039Combination Sum.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), 3 | find all unique combinations in candidates where the candidate numbers sums to target. 4 | The same repeated number may be chosen from candidates unlimited number of times. 5 | 6 | Input: candidates = [2,3,5], target = 8, 7 | A solution set is: 8 | [ [2,2,2,2], [2,3,3], [3,5] ] 9 | */ 10 | 11 | void helper(vector> &res,const vector& data, vector &path, int target, int cur){ 12 | if(target==0){ 13 | res.push_back(path); 14 | return; 15 | } 16 | for(int i=cur;i> combinationSum(vector& candidates, int target) { 25 | sort(candidates.begin(),candidates.end()); 26 | vector> res; 27 | vector path; 28 | helper(res, candidates, path, target, 0); 29 | return res; 30 | } 31 | -------------------------------------------------------------------------------- /code/0040Combination Sum II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of candidate numbers (candidates) and a target number (target), 3 | find all unique combinations in candidates where the candidate numbers sums to target. 4 | 5 | Each number in candidates may only be used once in the combination. 6 | 7 | Input: candidates = [10,1,2,7,6,1,5], target = 8, 8 | A solution set is: 9 | [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] 10 | */ 11 | 12 | void helper(vector> &res,const vector& data, vector &path, int target, int cur){ 13 | if(target==0){ 14 | res.push_back(path); 15 | return; 16 | } 17 | for(int i=cur;i> combinationSum2(vector& candidates, int target) { 29 | sort(candidates.begin(),candidates.end()); 30 | vector> res; 31 | vector path; 32 | helper(res, candidates, path, target, 0); 33 | return res; 34 | } 35 | -------------------------------------------------------------------------------- /code/0043. Multiply Strings.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, 3 | also represented as a string. 4 | 5 | Input: num1 = "2", num2 = "3" 6 | Output: "6" 7 | 8 | Input: num1 = "123", num2 = "456" 9 | Output: "56088" 10 | */ 11 | 12 | string multiply(string num1, string num2) { 13 | int n=num1.size(),m=num2.size(); 14 | vector data(n+m,0); 15 | for(int i=0;i=1 && res[n]=='0'){ 28 | n--; 29 | } 30 | res=res.substr(0,n+1); 31 | reverse(res.begin(),res.end()); 32 | return res; 33 | } 34 | -------------------------------------------------------------------------------- /code/0045. Jump Game II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | Each element in the array represents your maximum jump length at that position. 4 | Your goal is to reach the last index in the minimum number of jumps. 5 | 6 | Input: [2,3,1,1,4] 7 | Output: 2 8 | Explanation: The minimum number of jumps to reach the last index is 2. 9 | Jump 1 step from index 0 to 1, then 3 steps to the last index. 10 | 11 | Note: 12 | You can assume that you can always reach the last index. 13 | */ 14 | 15 | int jump(vector& nums) { 16 | //greedy 17 | int n=nums.size(); 18 | if(n<=1) return 0; 19 | int end=0,jump=0,next_end=0; 20 | for(int i=0;i=n-1) return jump+1; 23 | if(i==end){ 24 | jump++; 25 | end=next_end; 26 | } 27 | } 28 | return jump; 29 | } 30 | -------------------------------------------------------------------------------- /code/0046. Permutations.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of distinct integers, return all possible permutations. 3 | 4 | Input: [1,2,3] 5 | Output: 6 | [ [1,2,3], 7 | [1,3,2], 8 | [2,1,3], 9 | [2,3,1], 10 | [3,1,2], 11 | [3,2,1] ] 12 | */ 13 | 14 | void helper(vector> &res, vector& nums, int length, int cur){ 15 | if(cur==length-1){ 16 | res.push_back(nums); 17 | return; 18 | } 19 | for(int i=cur;i> permute(vector& nums) { 27 | vector> res; 28 | helper(res,nums,nums.size(),0); 29 | return res; 30 | } 31 | -------------------------------------------------------------------------------- /code/0047. Permutations II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 3 | 4 | Input: [1,1,2] 5 | Output: 6 | [ [1,1,2], [1,2,1], [2,1,1] ] 7 | */ 8 | void helper(vector> &res, vector& nums, int length, int cur){ 9 | if(cur==length-1){ 10 | res.push_back(nums); 11 | return; 12 | } 13 | unordered_map used; 14 | for(int i=cur;i> permuteUnique(vector& nums) { 24 | vector> res; 25 | helper(res,nums,nums.size(),0); 26 | return res; 27 | } 28 | -------------------------------------------------------------------------------- /code/0055. Jump Game.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | Each element in the array represents your maximum jump length at that position. 4 | 5 | Determine if you are able to reach the last index. 6 | 7 | Input: [2,3,1,1,4] 8 | Output: true 9 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 10 | */ 11 | 12 | bool canJump(vector& nums) { 13 | int n=nums.size(); 14 | int maxindex=nums[0]; 15 | for(int i=0;i<=min(n-1,maxindex);i++){ 16 | maxindex=max(maxindex,i+nums[i]); 17 | } 18 | return (maxindex>=n-1); 19 | } 20 | -------------------------------------------------------------------------------- /code/0060. Permutation Sequence.h: -------------------------------------------------------------------------------- 1 | /* 2 | The set [1,2,3,...,n] contains a total of n! unique permutations. 3 | By listing and labeling all of the permutations in order, we get the following sequence for n = 3: 4 | "123" 5 | "132" 6 | "213" 7 | "231" 8 | "312" 9 | "321" 10 | Given n and k, return the kth permutation sequence. 11 | 12 | Given n will be between 1 and 9 inclusive. 13 | Given k will be between 1 and n! inclusive. 14 | 15 | Input: n = 3, k = 3 16 | Output: "213" 17 | 18 | Input: n = 4, k = 9 19 | Output: "2314" 20 | */ 21 | 22 | class Solution { 23 | private: 24 | void helper(string & res, unordered_set& visited, int total, int n, int k){ 25 | if(0==n) return; 26 | int m=k/total+1,count=0,i=1; 27 | while(count visited; 39 | string res=""; 40 | int total=1; 41 | //total is (N-1)!, cut into group by first number, the number in a group 42 | for(int i=1;ix/mid) 22 | end=mid; 23 | else 24 | start=mid+1; 25 | } 26 | return start-1; 27 | } 28 | -------------------------------------------------------------------------------- /code/0072Edit Distance.h: -------------------------------------------------------------------------------- 1 | /* 2 | Share 3 | Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. 4 | You have the following 3 operations permitted on a word: 5 | Insert a character 6 | Delete a character 7 | Replace a character 8 | Example 1: 9 | 10 | Input: word1 = "horse", word2 = "ros" 11 | Output: 3 12 | Explanation: 13 | horse -> rorse (replace 'h' with 'r') 14 | rorse -> rose (remove 'r') 15 | rose -> ros (remove 'e') 16 | */ 17 | 18 | int minDistance(string word1, string word2) { 19 | int n=word1.size(),m=word2.size(); 20 | 21 | vector> dp(n+1,vector(m+1,0)); 22 | 23 | for(int i=0;i m; 15 | for(auto ii:t) 16 | m[ii]++; 17 | string res=""; 18 | //count means how many char is not fully covered 19 | int count=m.size(),start=0; 20 | 21 | for(int i=0;i> &res, vector &path, int pos, int n, int k){ 11 | if(path.size()==k) 12 | res.emplace_back(path); 13 | else if(k-path.size()<=(n-pos+1)){ 14 | dfs(res,path,pos+1,n,k); 15 | path.push_back(pos); 16 | dfs(res,path,pos+1,n,k); 17 | path.pop_back(); 18 | } 19 | return; 20 | } 21 | public: 22 | vector> combine(int n, int k) { 23 | vector> res; 24 | if(!n || !k) return res; 25 | vector path; 26 | dfs(res,path,1,n,k); 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /code/0078. Subsets.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of distinct integers, nums, return all possible subsets (the power set). 3 | Note: The solution set must not contain duplicate subsets. 4 | 5 | Input: nums = [1,2,3] 6 | Output: 7 | [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] 8 | */ 9 | 10 | void helper(vector> &res, vector &nums, vector &path, int cur){ 11 | if(cur==nums.size()){ 12 | res.push_back(path); 13 | return; 14 | } 15 | helper(res,nums,path,cur+1); 16 | path.push_back(nums[cur]); 17 | helper(res,nums,path,cur+1); 18 | path.pop_back(); 19 | } 20 | 21 | vector> subsets(vector& nums) { 22 | vector> res; 23 | vector path; 24 | helper(res,nums,path,0); 25 | return res; 26 | } 27 | -------------------------------------------------------------------------------- /code/0079. Word Search.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D board and a word, find if the word exists in the grid. 3 | The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or 4 | vertically neighboring. The same letter cell may not be used more than once. 5 | 6 | board = [ ['A','B','C','E'], 7 | ['S','F','C','S'], 8 | ['A','D','E','E'] ] 9 | 10 | Given word = "ABCCED", return true. 11 | Given word = "SEE", return true. 12 | Given word = "ABCB", return false. 13 | */ 14 | bool backtrack(vector>& board, string & word, int row,int col,int pos){ 15 | if(word[pos]!=board[row][col]) return false; 16 | if(pos==word.size()-1) 17 | return true; 18 | 19 | int n=board.size(),m=board[0].size(); 20 | char cur=board[row][col]; 21 | board[row][col]='*'; 22 | vector> direction={{1,0},{-1,0},{0,1},{0,-1}}; 23 | for(auto i:direction){ 24 | int x=row+i[0],y=col+i[1]; 25 | if(x>=0 && x=0 && y>& board, string word) { 33 | for(int i=0;i& heights) { 14 | //类似与longest increasing 15 | int n=heights.size(); 16 | if(n==0) return 0; 17 | stack data; 18 | data.push(-1);data.push(0); 19 | int res=0; 20 | for(int i=1;i heights[data.top()]) 23 | data.push(i); 24 | //要保证stack里前一个数是截至条件 25 | else if(heights[i]==heights[data.top()]) 26 | {data.pop(); data.push(i);} 27 | else{ 28 | while(data.size()>1 && heights[data.top()]>heights[i]){ 29 | int m=data.top(); 30 | data.pop(); 31 | //从要插入的位置建都比他大 32 | res=max(res,(i-1-data.top())*heights[m]); 33 | } 34 | data.push(i); 35 | } 36 | } 37 | //还剩下 38 | while(data.size()>1){ 39 | int m=data.top(); 40 | data.pop(); 41 | res=max(res,(n-1-data.top())*heights[m]); 42 | } 43 | return res; 44 | } 45 | -------------------------------------------------------------------------------- /code/0088. Merge Sorted Array.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 3 | 4 | Note: 5 | 6 | The number of elements initialized in nums1 and nums2 are m and n respectively. 7 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 8 | Example: 9 | 10 | Input: 11 | nums1 = [1,2,3,0,0,0], m = 3 12 | nums2 = [2,5,6], n = 3 13 | 14 | Output: [1,2,2,3,5,6] 15 | */ 16 | 17 | void merge(vector& nums1, int m, vector& nums2, int n) { 18 | int dist=n+m-1; //last element in nums1 need to move 19 | int i=m-1,j=n-1; 20 | while(j>=0){ 21 | //注意最后i指到-1 22 | //003000000 3 -1,11123 6 23 | if(i<0 || nums2[j]>nums1[i]){ 24 | nums1[dist--]=nums2[j--]; 25 | } 26 | else{ 27 | nums1[dist--]=nums1[i--]; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /code/0090. Subsets II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). 3 | Note: The solution set must not contain duplicate subsets. 4 | 5 | Input: [1,2,2] 6 | Output: 7 | [ [2], [1], [1,2,2], [2,2], [1,2], [] ] 8 | */ 9 | void helper(vector> &res, const unordered_map &m, vector &path, unordered_map::iterator cur){ 10 | if(cur==m.end()){ 11 | res.push_back(path); 12 | return; 13 | } 14 | auto pre=cur++; 15 | helper(res,m,path,cur); 16 | //加入不同的次数 17 | for(int i=0;isecond;i++){ 18 | path.push_back(pre->first); 19 | helper(res,m,path,cur); 20 | } 21 | //backtracking 22 | for(int i=0;isecond;i++) 23 | path.pop_back(); 24 | } 25 | vector> subsetsWithDup(vector& nums) { 26 | vector> res; 27 | unordered_map m; 28 | //用map变为没有重复的 29 | for(auto i:nums) 30 | m[i]++; 31 | vector path; 32 | helper(res,m,path,m.begin()); 33 | return res; 34 | } 35 | -------------------------------------------------------------------------------- /code/0091. Decode Ways.h: -------------------------------------------------------------------------------- 1 | /* 2 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | 'A' -> 1 4 | 'B' -> 2 5 | ... 6 | 'Z' -> 26 7 | Given a non-empty string containing only digits, determine the total number of ways to decode it. 8 | 9 | Input: "12" 10 | Output: 2 11 | 12 | Input: "226" 13 | Output: 3 14 | */ 15 | 16 | int numDecodings(string s) { 17 | int n=s.size(); 18 | vector res(n+1,0); 19 | if(n==0) 20 | return 0; 21 | //注意考虑‘0’ 22 | if(s[0]=='0') 23 | return 0; 24 | res[0]=res[1]=1; 25 | 26 | for(int i=2;i inorderTraversal(TreeNode* root) { 17 | vector res; 18 | stack s; 19 | //curr val和左右都没处理;stack 左侧处理,val和右侧没有处理 20 | //不停的将curr加stack,指向left, 21 | //没有指向的后,stack pop, 指向右侧 22 | TreeNode* curr=root; 23 | while(curr!=NULL || !s.empty()){ 24 | if(curr!=NULL){ 25 | s.push(curr); 26 | curr=curr->left; 27 | } 28 | else{ 29 | res.push_back(s.top()->val); 30 | curr=s.top()->right; 31 | s.pop(); 32 | } 33 | 34 | } 35 | return res; 36 | } 37 | -------------------------------------------------------------------------------- /code/0096Unique Binary Search Trees.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? 3 | 4 | Example: 5 | 6 | Input: 3 7 | Output: 5 8 | Explanation: 9 | Given n = 3, there are a total of 5 unique BST's: 10 | 11 | 1 3 3 2 1 12 | \ / / / \ \ 13 | 3 2 1 1 3 2 14 | / / \ \ 15 | 2 1 2 3 16 | */ 17 | int numTrees(int n) { 18 | //BST 特征,如果k是root, 1 to k-1在左,k+1 to n 在右侧 19 | //F(n)=F(0)*F(n-1)+F(1)*F(n-2)+..+F(n-1)F(0) 20 | if(n==0 ) return 1; 21 | vector nums(n+1,0); 22 | nums[0]=1; 23 | for(int i=1;i> data(n+1,vector(m+1,true)); 25 | for(int i=1;ileft,prev)) return false; 17 | if(prev && root->val<=prev->val) return false; 18 | prev=root; 19 | return valid(root->right,prev); 20 | } 21 | public: 22 | bool isValidBST(TreeNode* root) 23 | { 24 | TreeNode* prev = NULL; 25 | return valid(root, prev); 26 | } 27 | }; 28 | /* 29 | //range 20ms 30 | class Solution 31 | { 32 | private: 33 | bool valid(TreeNode* root, long mi, long ma) 34 | { 35 | if(root==NULL) return true; 36 | if((root->val<=ma)&&( root->val>=mi)) 37 | return valid(root->left,mi,(long)root->val-1) && valid(root->right,(long)root->val+1,ma); 38 | else 39 | return false; 40 | } 41 | public: 42 | bool isValidBST(TreeNode* root) 43 | { 44 | return valid(root,INT_MIN,INT_MAX); 45 | } 46 | }; 47 | */ 48 | -------------------------------------------------------------------------------- /code/0099. Recover Binary Search Tree.h: -------------------------------------------------------------------------------- 1 | /* 2 | Two elements of a binary search tree (BST) are swapped by mistake. 3 | Recover the tree without changing its structure. 4 | */ 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | private: 17 | void tranversal(TreeNode *root, TreeNode* &prev, TreeNode* &find1,TreeNode* &find2){ 18 | if(!root) return; 19 | tranversal(root->left,prev,find1,find2); 20 | if(prev && prev->val>root->val){ 21 | if(!find1) find1=prev; 22 | find2=root; 23 | } 24 | prev=root; 25 | tranversal(root->right,prev,find1,find2); 26 | } 27 | public: 28 | void recoverTree(TreeNode* root) { 29 | //4,2,3,1 30 | //3,2,1 31 | //1,3,2,4 32 | TreeNode *find1=NULL, *find2=NULL, *prev=NULL; 33 | tranversal(root, prev,find1,find2); 34 | swap(find1->val,find2->val); 35 | return; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /code/0107. Binary Tree Level Order Traversal II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 3 | 4 | For example: 5 | Given binary tree [3,9,20,null,null,15,7], 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | return its bottom-up level order traversal as: 12 | [ 13 | [15,7], 14 | [9,20], 15 | [3] 16 | ] 17 | */ 18 | class Solution { 19 | public: 20 | void levelOrder(vector> &ans, TreeNode *node, int level) { 21 | if (!node) return; 22 | if (level >= ans.size()) 23 | ans.push_back({}); 24 | ans[level].push_back(node->val); 25 | levelOrder(ans,node->left,level+1); 26 | levelOrder(ans,node->right,level+1); 27 | } 28 | 29 | vector> levelOrderBottom(TreeNode* root) { 30 | vector> ans; 31 | levelOrder(ans,root,0); 32 | reverse(ans.begin(),ans.end()); 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /code/0110. Balanced Binary Tree.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, determine if it is height-balanced. 3 | 4 | For this problem, a height-balanced binary tree is defined as: 5 | 6 | a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 7 | */ 8 | 9 | class Solution { 10 | private: 11 | bool res=1; 12 | int maxdepth(TreeNode* root) 13 | { 14 | if(!root) return 0; 15 | int leftdepth=maxdepth(root->left); 16 | int rightdepth=maxdepth(root->right); 17 | if(abs(leftdepth-rightdepth)>1) res=0; 18 | return max(leftdepth,rightdepth)+1; 19 | } 20 | public: 21 | bool isBalanced(TreeNode* root) 22 | { 23 | maxdepth(root); 24 | return res; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /code/0113. Path Sum II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 3 | Note: A leaf is a node with no children. 4 | 5 | 6 | Given the below binary tree and sum = 22, 7 | 8 | 5 9 | / \ 10 | 4 8 11 | / / \ 12 | 11 13 4 13 | / \ / \ 14 | 7 2 5 1 15 | Return: 16 | [ [5,4,11,2], [5,8,4,5] ] 17 | */ 18 | 19 | class Solution { 20 | private: 21 | void backtrack(vector> &res, vector &path,TreeNode* root,int sum, int target){ 22 | //如果是root且相等 23 | if(!root->left && !root->right){ 24 | if(root->val+sum==target){ 25 | path.push_back(root->val); 26 | res.push_back(path); 27 | //找到了不要忘记pop_back 28 | path.pop_back(); 29 | } 30 | return; 31 | } 32 | path.push_back(root->val); 33 | if(root->left) 34 | backtrack(res,path,root->left,sum+root->val,target); 35 | if(root->right) 36 | backtrack(res,path,root->right,sum+root->val,target); 37 | path.pop_back(); 38 | return; 39 | } 40 | public: 41 | vector> pathSum(TreeNode* root, int sum) { 42 | vector> res; 43 | vector path; 44 | if(root) 45 | backtrack(res,path, root, 0, sum); 46 | return res; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /code/0115. Distinct Subsequences.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S and a string T, count the number of distinct subsequences of S which equals T. 3 | A subsequence of a string is a new string which is formed from the original string 4 | by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. 5 | (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). 6 | */ 7 | 8 | int numDistinct(string s, string t) { 9 | // babgbag 10 | //b 1 1 1 11 | //a 1 3 12 | //g 1 4 13 | int m=s.size(),n=t.size(); 14 | if(m==0 || n==0) return 0; 15 | vector> dp(n+1,vector(m+1,0)); 16 | for(int i=1;i& prices) { 13 | int k=2; 14 | //state (buy+sell)*k 15 | int n=prices.size(); 16 | if(n<2 | k<1) return 0; 17 | //k特别大,不用那么多内存 18 | k=min(k,n/2); 19 | //买卖两种状态,k次 20 | vector state(2*k,INT_MIN); 21 | state[0]=-prices[0]; 22 | for(int i=1;ileft),r=helper(root->right); 27 | int cur=max(max(l+root->val,r+root->val),root->val); 28 | res=max(max(res,l+root->val+r),cur); 29 | return cur; 30 | } 31 | public: 32 | int maxPathSum(TreeNode* root) { 33 | helper(root); 34 | return res; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /code/0128. Longest Consecutive Sequence.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 3 | 4 | Your algorithm should run in O(n) complexity. 5 | 6 | Example: 7 | 8 | Input: [100, 4, 200, 1, 3, 2] 9 | Output: 4 10 | Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. 11 | */ 12 | 13 | int longestConsecutive(vector& nums) { 14 | int maxlength=0; 15 | // map 存0.在nums中出现,并且没扫过长度 16 | // map 存1.已经在最长subsequence里面update了 17 | unordered_map used; 18 | for (int num:nums) 19 | used[num]=0; 20 | 21 | for (int num:nums){ 22 | int length=0; 23 | if (used.find(num)!=used.end()&& used[num]==0){ 24 | used[num]=1; 25 | length++; 26 | int number=num; 27 | while(used.find(--num)!=used.end()){ 28 | length++; used[num]=1; 29 | } 30 | num=number; 31 | while(used.find(++num)!=used.end()){ 32 | length++; used[num]=1; 33 | } 34 | } 35 | maxlength=max(length,maxlength); 36 | } 37 | return maxlength; 38 | } 39 | -------------------------------------------------------------------------------- /code/0131. Palindrome Partitioning.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | Return all possible palindrome partitioning of s. 4 | 5 | Input: "aab" 6 | Output: [ ["aa","b"], ["a","a","b"] ] 7 | */ 8 | 9 | bool ispalindrome(const string &s,int begin,int end){ 10 | while(begin> &res,const string &s,vector &path,int cur){ 16 | if(cur==s.size()){ 17 | res.push_back(path); 18 | return; 19 | } 20 | for(int i=cur;i> partition(string s) { 29 | vector> res; 30 | if(s.size()==0) return res; 31 | vector path; 32 | helper(res,s,path,0); 33 | return res; 34 | } 35 | -------------------------------------------------------------------------------- /code/0132. Palindrome Partitioning II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | Return the minimum cuts needed for a palindrome partitioning of s. 4 | 5 | Input: "aab" 6 | Output: 1 7 | */ 8 | 9 | int minCut(string s) { 10 | int n=s.size(); 11 | if(n==0) return 0; 12 | vector count(n+1); //存0到i需要几次partition 13 | for(int i=0;i> dp(n,vector(n,0)); //s[i to j] 是否palindrome 16 | for(int i=0;i& gas, vector& cost) { 25 | //if sum positive, there must be a solution 26 | int total=0,sum=0,n=gas.size(),res=0; 27 | for(int i=0;i& nums) 15 | { 16 | int res=0; 17 | for(auto i:nums) 18 | res^=i; 19 | return res; 20 | } 21 | -------------------------------------------------------------------------------- /code/0137. Single Number II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty array of integers, every element appears three times except for one, 3 | which appears exactly once. Find that single one. 4 | 5 | 6 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 7 | 8 | Input: [2,2,3,2] 9 | Output: 3 10 | Example 2: 11 | 12 | Input: [0,1,0,1,0,1,99] 13 | Output: 99 14 | */ 15 | 16 | int singleNumber(vector& nums) { 17 | //a b num -> a b 18 | //0 0 0 0 0 19 | //0 1 0 0 1 20 | //1 0 0 1 0 21 | //0 0 1 0 1 22 | //0 1 1 1 0 23 | //1 0 1 0 0 24 | //a= b&c+a&~c 25 | //b= (~(a^b))&c+b&~c 26 | //加号是 | 27 | //或者 28 | //a = a&~b&~c + ~a&b&c; 29 | //b = ~a&b&~c + ~a&~b&c; 30 | int a=0,b=0; 31 | for(auto i:nums){ 32 | int temp=a; 33 | a= (b&i)|(a&~i); 34 | b= (~(temp^b)&i)|(b&~i); 35 | } 36 | return b; 37 | } 38 | -------------------------------------------------------------------------------- /code/0139. Word Break.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, 3 | determine if s can be segmented into a space-separated sequence of one or more dictionary words. 4 | 5 | The same word in the dictionary may be reused multiple times in the segmentation. 6 | You may assume the dictionary does not contain duplicate words. 7 | 8 | Input: s = "applepenapple", wordDict = ["apple", "pen"] 9 | Output: true 10 | */ 11 | 12 | bool wordBreak(string s, vector& wordDict) { 13 | //set data(wordDict); 14 | //set faster to find, better than vector. 15 | set data(wordDict.begin(),wordDict.end()); 16 | 17 | int n=s.size(); 18 | vector res(n+1); 19 | res[0]=true; 20 | for(int i=1;i preorderTraversal(TreeNode* root) { 16 | vector res; 17 | stack s; 18 | //先打印root 19 | //打印curr值 然后将curr的右加入stack, curr指向左侧 20 | //没有指向的后,指向stack top,pop 21 | TreeNode* curr=root; 22 | while(curr!=NULL || !s.empty()){ 23 | if(curr!=NULL){ 24 | res.push_back(curr->val); 25 | if(curr->right) s.push(curr->right); 26 | curr=curr->left; 27 | } 28 | else{ 29 | curr=s.top(); 30 | s.pop(); 31 | } 32 | 33 | } 34 | return res; 35 | } 36 | -------------------------------------------------------------------------------- /code/0145. Binary Tree Postorder Traversal.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the postorder traversal of its nodes' values. 3 | 4 | Example: 5 | 6 | Input: [1,null,2,3] 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | 13 | Output: [3,2,1] 14 | Follow up: Recursive solution is trivial, could you do it iteratively? 15 | */ 16 | 17 | vector postorderTraversal(TreeNode* root) { 18 | vector res; 19 | stack s; 20 | //先打印root,只比preorder, 最后reverse 21 | //打印curr值 然后将curr的左加入stack, curr指向右侧 22 | //没有指向的后,指向stack top,pop 23 | TreeNode* curr=root; 24 | while(curr!=NULL || !s.empty()){ 25 | if(curr!=NULL){ 26 | res.push_back(curr->val); 27 | if(curr->left) s.push(curr->left); 28 | curr=curr->right; 29 | } 30 | else{ 31 | curr=s.top(); 32 | s.pop(); 33 | } 34 | 35 | } 36 | reverse(res.begin(),res.end()); 37 | return res; 38 | } 39 | -------------------------------------------------------------------------------- /code/0151. Reverse Words in a String.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an input string, reverse the string word by word. 3 | 4 | Input: "the sky is blue" 5 | Output: "blue is sky the" 6 | 7 | Input: " hello world! " 8 | Output: "world! hello" 9 | 10 | Input: "a good example" 11 | Output: "example good a" 12 | */ 13 | 14 | string reverseWords(string s) { 15 | int pos=0,start=0, n=s.size(); 16 | 17 | string res; 18 | while(s[start]==' ') start++; 19 | //" a a " 20 | for(int i=start;i& nums) 21 | { 22 | int len=nums.size(); 23 | if(len==1) return nums[0]; 24 | 25 | int start=0,end=len-1; 26 | while (start& nums) { 20 | int len=nums.size(); 21 | if(len==1) return nums[0]; 22 | 23 | int start=0,end=len-1; 24 | while (start nToPos; //map n to position start recurring 19 | string s; 20 | int pos=0; 21 | while(n!=0){ 22 | if(nToPos.count(n)) 23 | return s.substr(0,nToPos[n])+'('+s.substr(nToPos[n])+')'; 24 | nToPos[n]=pos++; 25 | s+=(10*n)/m+'0'; 26 | n=(10*n)%m; 27 | } 28 | return s; 29 | } 30 | public: 31 | string fractionToDecimal(int numerator, int denominator) { 32 | //INT_MIN overflow 33 | long long n=numerator, m=denominator; 34 | if(n%m==0) return to_string(n/m); 35 | //分开处理符号 36 | string sign= ((abs(n)/n) * (abs(m)/m)==1)?"":"-"; 37 | n=abs(n),m=abs(m); 38 | return sign+to_string(n/m)+'.'+helper(abs(n%m),m); // -50 /8 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /code/0173. Binary Search Tree Iterator.h: -------------------------------------------------------------------------------- 1 | /* 2 | Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. 3 | 4 | Calling next() will return the next smallest number in the BST. 5 | 6 | next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 7 | You may assume that next() call will always be valid, that is, 8 | there will be at least a next smallest number in the BST when next() is called. 9 | */ 10 | 11 | class BSTIterator { 12 | private: 13 | stack s; 14 | public: 15 | BSTIterator(TreeNode* root) { 16 | getmin(root); 17 | } 18 | 19 | /** @return the next smallest number */ 20 | int next() { 21 | int res=s.top()->val; 22 | TreeNode* p=s.top(); 23 | s.pop(); 24 | getmin(p->right); 25 | return res; 26 | } 27 | 28 | /** @return whether we have a next smallest number */ 29 | bool hasNext() { 30 | return !s.empty(); 31 | } 32 | 33 | void getmin(TreeNode* root){ 34 | TreeNode* p=root; 35 | while(p) { 36 | s.push(p); 37 | p=p->left; 38 | } 39 | return; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /code/0188. Best Time to Buy and Sell Stock IV.h: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | Design an algorithm to find the maximum profit. You may complete at most k transactions. 4 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 5 | */ 6 | 7 | int maxProfit(int k, vector& prices) { 8 | //state (buy+sell)*k 9 | int n=prices.size(); 10 | if(n<2 | k<1) return 0; 11 | //k特别大,不用那么多内存 12 | k=min(k,n/2); 13 | //买卖两种状态,k次 14 | vector state(2*k,INT_MIN); 15 | state[0]=-prices[0]; 16 | for(int i=1;i a(n); 18 | string s=a.to_string(); 19 | reverse(s.begin(),s.end()); 20 | bitset<32> b(s); 21 | return b.to_ulong(); 22 | */ 23 | uint32_t res=0; 24 | for(int i=0;i<32;i++){ 25 | res=(res<<1)+((n>>i)&1); 26 | } 27 | return res; 28 | } 29 | -------------------------------------------------------------------------------- /code/0198House Robber.h: -------------------------------------------------------------------------------- 1 | /* 2 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, 3 | the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and 4 | it will automatically contact the police if two adjacent houses were broken into on the same night. 5 | 6 | Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money 7 | you can rob tonight without alerting the police. 8 | */ 9 | 10 | int rob(vector& nums) { 11 | //sum[i]=max(sum[i-1], sum[i-2]+nums[i], sum[i-3]+nums[i]) 12 | int n=nums.size(); 13 | if(n==0) 14 | return 0; 15 | if(n==1) 16 | return nums[0]; 17 | if(n==2) 18 | return max(nums[0],nums[1]); 19 | if(n==3) 20 | return max(nums[1],nums[0]+nums[2]); 21 | else{ 22 | vector result(n); 23 | result[0]=nums[0]; 24 | result[1]=max(nums[0],nums[1]); 25 | result[2]=max(nums[1],nums[0]+nums[2]); 26 | for(int i=3;i> &res,vector &path,int target, int length, int cur){ 9 | if(target==0 && length==0){ 10 | res.push_back(path); 11 | return; 12 | } 13 | if(length==0) 14 | return; 15 | for(int i=cur; i<10 && target>=(i+i+length-1)*length/2;i++){ 16 | path.push_back(i); 17 | helper(res,path,target-i,length-1,i+1); 18 | path.pop_back(); 19 | } 20 | return; 21 | } 22 | 23 | vector> combinationSum3(int k, int n) { 24 | vector> res; 25 | vector path; 26 | helper(res,path,n,k,1); 27 | return res; 28 | } 29 | -------------------------------------------------------------------------------- /code/0221. Maximal Square.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 3 | 4 | 1 0 1 0 0 5 | 1 0 1 1 1 6 | 1 1 1 1 1 7 | 1 0 0 1 0 8 | 9 | Output: 4 10 | */ 11 | 12 | int maximalSquare(vector>& matrix) { 13 | //DP 两个row 存数据,不用m*n 14 | //到这点的最大的square 15 | int res=0; 16 | int n=matrix.size(); 17 | if(n==0) return 0; 18 | int m=matrix[0].size(); 19 | vector prev(m+1,0); 20 | for(int i=0;i curr(m+1,0); 27 | for(int j=1;jE & G>A & D>F & H>B) 12 | return res-(min(C,G)-max(A,E))*(min(D,H)-max(F,B)); 13 | else 14 | return res; 15 | } 16 | -------------------------------------------------------------------------------- /code/0227. Basic Calculator II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Implement a basic calculator to evaluate a simple expression string. 3 | 4 | The expression string contains only non-negative integers, +, -, *, / operators and empty spaces. 5 | The integer division should truncate toward zero. 6 | 7 | Input: "3+2*2" 8 | Output: 7 9 | 10 | Input: " 3/2 " 11 | Output: 1 12 | 13 | Input: " 3+5 / 2 " 14 | Output: 5 15 | 16 | Note: 17 | You may assume that the given expression is always valid. 18 | Do not use the eval built-in library function. 19 | */ 20 | 21 | int calculate(string s) { 22 | int n=s.size(); 23 | stack s1;stack s2; 24 | for(int i=0;ileft,k); 18 | if(res!=-1) return res; 19 | if(!(--k)) return root->val; 20 | return kthSmallest(root->right,k); 21 | } 22 | -------------------------------------------------------------------------------- /code/0231. Power of Two.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer, write a function to determine if it is a power of two. 3 | 4 | Input: 1 5 | Output: true 6 | 7 | Input: 16 8 | Output: true 9 | 10 | Input: 218 11 | Output: false 12 | */ 13 | 14 | bool isPowerOfTwo(int n) { 15 | if(n<=0) return false; 16 | return (n&(n-1))==0; 17 | } 18 | -------------------------------------------------------------------------------- /code/0234. Palindrome Linked List.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a singly linked list, determine if it is a palindrome. 3 | 4 | Input: 1->2 5 | Output: false 6 | Example 2: 7 | 8 | Input: 1->2->2->1 9 | Output: true 10 | Follow up: 11 | Could you do it in O(n) time and O(1) space? 12 | */ 13 | 14 | bool isPalindrome(ListNode* head) { 15 | //1 2 2 1 16 | //1 2 1 17 | if(!head) return true; 18 | 19 | ListNode* slow=head,*fast=head; 20 | while(fast && fast->next){ 21 | slow=slow->next; 22 | fast=fast->next->next; 23 | } 24 | //reverse fast to end; 25 | ListNode* head2=slow; 26 | while(slow->next){ 27 | ListNode* temp=slow->next->next; 28 | slow->next->next=head2; 29 | head2=slow->next; 30 | slow->next=temp; 31 | } 32 | while(head2){ 33 | if(head->val==head2->val){ 34 | head=head->next; 35 | head2=head2->next; 36 | } 37 | else return false; 38 | } 39 | return true; 40 | } 41 | -------------------------------------------------------------------------------- /code/0235. Lowest Common Ancestor of a Binary Search Tree.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 3 | According to the definition of LCA on Wikipedia: 4 | “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants 5 | (where we allow a node to be a descendant of itself).” 6 | Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5] 7 | 8 | Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 9 | Output: 6 10 | 11 | Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 12 | Output: 2 13 | Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. 14 | */ 15 | 16 | class Solution { 17 | //root 的范围 l r 18 | void helper(TreeNode* root,TreeNode* &res,TreeNode* p,TreeNode* q,int l,int r){ 19 | if(p->val>l && q->val>l && p->valvalleft) helper(root->left, res, p, q, l,root->val); 22 | if(root->right) helper(root->right, res, p, q, root->val,r); 23 | } 24 | return; 25 | } 26 | public: 27 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 28 | TreeNode* res=root; 29 | helper(root,res,p,q,INT_MIN,INT_MAX); 30 | return res; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /code/0256Paint House.h: -------------------------------------------------------------------------------- 1 | /* 2 | There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. 3 | The cost of painting each house with a certain color is different. You have to paint all the houses such that 4 | no two adjacent houses have the same color. 5 | The cost of painting each house with a certain color is represented by a n x 3 cost matrix. 6 | For example, costs[0][0] is the cost of painting house 0 with color red; 7 | costs[1][2] is the cost of painting house 1 with color green, and so on... 8 | Find the minimum cost to paint all houses. 9 | 10 | Note: 11 | All costs are positive integers. 12 | 13 | Example: 14 | Input: [[17,2,17],[16,16,5],[14,3,19]] 15 | Output: 10 16 | Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. 17 | Minimum cost: 2 + 5 + 3 = 10. 18 | */ 19 | 20 | int minCost(vector>& costs) { 21 | int n=costs.size(); 22 | if(n==0) return 0; 23 | for(int i=1;i2->5", "1->3"] 12 | Explanation: All root-to-leaf paths are: 1->2->5, 1->3 13 | */ 14 | 15 | class Solution { 16 | private: 17 | void backtrack(vector &res, string &path,TreeNode* root){ 18 | path+=((!path.size())?"":"->")+to_string(root->val); 19 | if(!(root->left)&&!(root->right)) 20 | res.push_back(path); 21 | else{ 22 | if(root->left) 23 | backtrack(res,path,root->left); 24 | if(root->right) 25 | backtrack(res,path,root->right); 26 | } 27 | while(path.size() && path.back()>='0' && path.back()<='9') 28 | path.pop_back(); 29 | while(path.size() && (path.back()=='>' || path.back()=='-') ) 30 | path.pop_back(); 31 | return; 32 | } 33 | public: 34 | vector binaryTreePaths(TreeNode* root) { 35 | vector res; 36 | string path=""; 37 | if(root) 38 | backtrack(res,path,root); 39 | return res; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /code/0260. Single Number III.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. 3 | Find the two elements that appear only once. 4 | 5 | Input: [1,2,1,3,2,5] 6 | Output: [3,5] 7 | 8 | The order of the result is not important. So in the above example, [5, 3] is also correct. 9 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 10 | */ 11 | 12 | vector singleNumber(vector& nums) { 13 | //a^b 不同的地方是 1 14 | int diff=0; 15 | for(auto i:nums) 16 | diff^=i; 17 | //1 0 1 0 0 0 先-1 18 | //1 0 0 1 1 1 ~ 19 | //0 1 1 0 0 0 and 20 | //0 0 1 0 0 0 21 | diff &= ~(diff-1); //找出一个不同的digit 22 | vector res(2,0); 23 | for(auto i:nums){ 24 | if(i&diff) //有着 25 | res[0]^=i; 26 | else 27 | res[1]^=i; 28 | } 29 | return res; 30 | } 31 | -------------------------------------------------------------------------------- /code/0268. Missing Number.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 3 | 4 | Input: [3,0,1] 5 | Output: 2 6 | Example 2: 7 | 8 | Input: [9,6,4,2,3,5,7,0,1] 9 | Output: 8 10 | 11 | Note: 12 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 13 | */ 14 | 15 | int missingNumber(vector& nums) { 16 | int n=nums.size(),res=0; 17 | for(int i=0;i& nums) { 26 | int n=nums.size(); 27 | int sum=0; 28 | for(auto i:nums) 29 | sum+=i; 30 | return n*(n+1)/2-sum; 31 | } 32 | */ 33 | -------------------------------------------------------------------------------- /code/0275H-Index II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, 3 | write a function to compute the researcher's h-index. 4 | 5 | According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, 6 | and the other N − h papers have no more than h citations each." 7 | 8 | Input: citations = [0,1,3,5,6] 9 | Output: 3 10 | Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had 11 | received 0, 1, 3, 5, 6 citations respectively. 12 | Since the researcher has 3 papers with at least 3 citations each and the remaining 13 | two with no more than 3 citations each, her h-index is 3. 14 | */ 15 | 16 | int hIndex(vector& citations) { 17 | int n=citations.size(); 18 | if(n==0 || citations[n-1]==0) return 0; 19 | int left=0,right=n,mid; 20 | while(left=(n-mid)) 23 | right=mid; 24 | else 25 | left=mid+1; 26 | } 27 | return n-left; 28 | } 29 | -------------------------------------------------------------------------------- /code/0276Paint Fence.h: -------------------------------------------------------------------------------- 1 | /* 2 | There is a fence with n posts, each post can be painted with one of the k colors. 3 | You have to paint all the posts such that no more than two adjacent fence posts have the same color. 4 | Return the total number of ways you can paint the fence. 5 | */ 6 | 7 | int numWays(int n, int k) { 8 | //no three are same 9 | //multiple two same are ok. 10 | //DP, two states:same as last, different from last. states add one more degree: 1D to 2D 11 | //memory 2D 压缩为 1D 12 | 13 | if(n<1||k<1) return 0; 14 | if(n==1) return k; 15 | else if(n==2) return k*k; 16 | else{ 17 | //same as last one 18 | int same=k; 19 | int diff=k*(k-1); 20 | for(int i=2;i false 15 | call isBadVersion(5) -> true 16 | call isBadVersion(4) -> true 17 | Then 4 is the first bad version. 18 | */ 19 | 20 | int firstBadVersion(int n) { 21 | int start=1,end=n,mid; 22 | while(start dp(n+1,INT_MAX); 8 | for(int i=1;ival>p->val){ 12 | if(root->left) 13 | res=helper(root->left,prev,p); 14 | } 15 | if(res) return res; 16 | if(prev==p) return root; 17 | prev=root; 18 | if(root->right) 19 | res=helper(root->right,prev,p); 20 | if(res) return res; 21 | return NULL; 22 | } 23 | public: 24 | TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { 25 | TreeNode *prev=NULL; 26 | return helper(root,prev,p); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /code/0300. Longest Increasing Subsequence.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted array of integers, find the length of longest increasing subsequence. 3 | 4 | Input: [10,9,2,5,3,7,101,18] 5 | Output: 4 6 | Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 7 | */ 8 | 9 | int lengthOfLIS(vector& nums) { 10 | int n=nums.size(); 11 | vector sorted; 12 | for(int i:nums){ 13 | //binary search sorted vector, find not less than or end 14 | auto iter=lower_bound(sorted.begin(),sorted.end(),i); 15 | if(iter==sorted.end()) 16 | sorted.push_back(i); 17 | else 18 | *iter=i; 19 | } 20 | return sorted.size(); 21 | } 22 | -------------------------------------------------------------------------------- /code/0301. Remove Invalid Parentheses.h: -------------------------------------------------------------------------------- 1 | /* 2 | Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. 3 | Note: The input string may contain letters other than the parentheses ( and ). 4 | 5 | 6 | Input: "()())()" 7 | Output: ["()()()", "(())()"] 8 | 9 | Input: "(a)())()" 10 | Output: ["(a)()()", "(a())()"] 11 | 12 | Input: ")(" 13 | Output: [""] 14 | */ 15 | 16 | void dfs(vector &res, string s, int pos,int lastRm, string dir){ 17 | //看不懂这个最优答案 18 | for(int i=pos,count=0;i=0) continue; 22 | 23 | //从上一次remove的开始,到i,多一个的位置 24 | for(int j=lastRm;j<=i;j++){ 25 | if(s[j]==dir[1] && (j==lastRm || s[j-1]!=dir[1])) // && 后面去重复的 26 | dfs(res,s.substr(0,j)+s.substr(j+1),i,j,dir); //新的i是count=0的位置了,j是remove后的下一位 27 | } 28 | return; 29 | } 30 | reverse(s.begin(),s.end()); 31 | //一个都没remove才能走到这 32 | if(dir[0]=='(') dfs(res,s,0,0,")("); 33 | else res.push_back(s); //只有 ")(" 一次没remove才能走到这 34 | } 35 | public: 36 | vector removeInvalidParentheses(string s) { 37 | vector res; 38 | dfs(res,s,0,0,"()"); 39 | return res; 40 | } 41 | -------------------------------------------------------------------------------- /code/0309. Best Time to Buy and Sell Stock with Cooldown.h: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like 4 | (ie, buy one and sell one share of the stock multiple times) with the following restrictions: 5 | 6 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 7 | After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day) 8 | 9 | Input: [1,2,3,0,2] 10 | Output: 3 11 | Explanation: transactions = [buy, sell, cooldown, buy, sell] 12 | */ 13 | 14 | int maxProfit(vector& prices) { 15 | // 1 2 3 0 2 16 | //buy -1 -1 -1 1 1 17 | //sell min 1 2 2 3 18 | //reset 0 0 1 2 2 19 | int n=prices.size(); 20 | if(n<=1) return 0; 21 | int buy=-prices[0]; 22 | int sell=INT_MIN,reset=0; 23 | int pre_buy,pre_sell; 24 | //buy 要在reset后面,reset是max pre_sell, 意味着之前卖过 25 | //reset[i]=max(reset[i-1], buy[i-1]) 26 | //buy[i]=max(buy[i-1], reset[i-1]-prices[i]) 27 | for(int i=1;i> multiply(vector>& A, vector>& B) { 29 | int n=A.size(),k=A[0].size(),m=B[0].size(); 30 | vector> res(n,vector(m,0)); 31 | unordered_map>> mA,mB; 32 | for(int i=0;i> &m, int pos, TreeNode* root){ 9 | if(!root) return; 10 | m[pos].push_back(root->val); 11 | helper(m,pos-1,root->left); 12 | helper(m,pos+1,root->right); 13 | } 14 | public: 15 | vector> verticalOrder(TreeNode* root) { 16 | vector> res; 17 | map> m; 18 | queue> q; 19 | if(!root) return res; 20 | q.push({0,root}); 21 | while(!q.empty()){ 22 | int pos=q.front().first; 23 | m[pos].push_back(q.front().second->val); 24 | if(q.front().second->left) 25 | q.push(make_pair(pos-1,q.front().second->left)); 26 | if(q.front().second->right) 27 | q.push(make_pair(pos+1,q.front().second->right)); 28 | q.pop(); 29 | } 30 | for(auto i:m) 31 | res.push_back(i.second); 32 | return res; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /code/0315. Count of Smaller Numbers After Self.h: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer array nums and you have to return a new counts array. 3 | The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. 4 | 5 | Input: [5,2,6,1] 6 | Output: [2,1,1,0] 7 | */ 8 | 9 | class Solution { 10 | private: 11 | void mergesort(vector> &data, int l, int r,vector &res){ 12 | if(r-l<=1) return; 13 | int mid=(r-l)/2+l; 14 | mergesort(data,l,mid,res); 15 | mergesort(data,mid,r,res); 16 | int start=mid; 17 | for(int i=l;idata[start][0]) start++; 19 | res[data[i][1]]+=(start-mid); 20 | } 21 | inplace_merge(data.begin()+l,data.begin()+mid,data.begin()+r); 22 | return; 23 | } 24 | public: 25 | vector countSmaller(vector& nums) { 26 | int n=nums.size(); 27 | vector> data(n,vector(2,0)); 28 | for(int i=0;i res(n,0); 33 | mergesort(data,0,n,res); 34 | return res; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /code/0327. Count of Range Sum.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive. 3 | Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive. 4 | 5 | A naive algorithm of O(n2) is trivial. You MUST do better than that. 6 | 7 | Input: nums = [-2,5,-1], lower = -2, upper = 2, 8 | Output: 3 9 | */ 10 | 11 | class Solution { 12 | private: 13 | int mergesort(vector& sums, int lower, int upper,int l, int r){ 14 | if(r-l<=1) return 0; 15 | int mid=l+(r-l)/2,count=0,m=mid,n=mid; 16 | count=count+mergesort(sums,lower,upper,l,mid)+ 17 | mergesort(sums,lower,upper,mid,r); 18 | for(int i=l;i& nums, int lower, int upper) { 28 | int n=nums.size(); 29 | //sums 最前面必须是0,不然不会包括只有一个element的sub_array 30 | vector sums(n+1,0); 31 | for(int i=0; i>& matrix,vector>& visited,int i,int j){ 19 | if(visited[i][j]>0) return visited[i][j]; 20 | int n=matrix.size(); 21 | int m=matrix[0].size(); 22 | visited[i][j]=1; 23 | vector pos={1,0,-1,0,1}; 24 | for(int k=0;k<4;k++){ 25 | int y=i+pos[k],x=j+pos[k+1]; 26 | if(y>-1 && y-1 && xmatrix[i][j]) 27 | visited[i][j]=max(visited[i][j], 1+dfs(matrix,visited,y,x)); 28 | } 29 | return visited[i][j]; 30 | } 31 | int longestIncreasingPath(vector>& matrix){ 32 | int n=matrix.size(); 33 | if(n==0) return 0; 34 | int m=matrix[0].size(),maxlen=0; 35 | vector> visited(n,vector(m,0)); 36 | //dfs position 37 | 38 | for(int i=0;i countBits(int num) { 15 | vector result(num+1,0); 16 | for(int i=1;i countBits(int num) { 23 | vector result(num+1,0); 24 | for(int i=1;i m; 12 | int start=0; 13 | int end=0; 14 | int maxlen=0; 15 | for(;endk){ 18 | m[s[start]]--; 19 | if(m[s[start]]==0) 20 | m.erase(m.find(s[start])); 21 | start++; 22 | } 23 | maxlen=max(maxlen,end-start+1); 24 | } 25 | return maxlen; 26 | } 27 | -------------------------------------------------------------------------------- /code/0342. Power of Four.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 3 | 4 | Input: 16 5 | Output: true 6 | 7 | Input: 5 8 | Output: false 9 | */ 10 | 11 | bool isPowerOfFour(int n) { 12 | if(n<0) return false; 13 | // 1 14 | // 100 15 | // 10000 16 | // n&(n-1) 只有一个one | n&0x55555555 1只能在基数位 17 | // F = 0x55555555 = 01010101010101010101010101010101 18 | // T = 0x33333333 = 00110011001100110011001100110011 19 | // O = 0x0f0f0f0f = 00001111000011110000111100001111 20 | return !(n&(n-1)) && (n&0x55555555); 21 | } 22 | -------------------------------------------------------------------------------- /code/0343. Integer Break.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. 3 | Return the maximum product you can get. 4 | Input: 10 5 | Output: 36 6 | Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. 7 | */ 8 | 9 | int integerBreak(int n) { 10 | //2 1*1=1 11 | //3 2*1=2 12 | //4 2*2=4 13 | //5 2*3=6 14 | //6 3*3=9 15 | //只有2,3变小,不能分解,其他都可以,所以dp check -2 -3 16 | if(n==2) return 1; 17 | if(n==3) return 2; 18 | if(n==4) return 4; 19 | if(n==5) return 6; 20 | if(n==6) return 9; 21 | vector dp(n+1); 22 | dp[2]=1;dp[3]=2;dp[4]=4;dp[5]=6;dp[6]=9; 23 | for(int i=7;i [5,4] => [6,7]). 13 | */ 14 | 15 | int maxEnvelopes(vector>& envelopes) { 16 | //lambda 17 | sort(envelopes.begin(),envelopes.end(),[](pair a, pair b){ 18 | return (a.firstb.second);}); 19 | //6,7 before 6,4 20 | vector sorted; 21 | for (auto ii: envelopes){ 22 | auto iter=lower_bound(sorted.begin(),sorted.end(),ii.second); 23 | if(iter==sorted.end()) 24 | sorted.push_back(ii.second); 25 | else 26 | *iter=ii.second; 27 | } 28 | return sorted.size(); 29 | } 30 | -------------------------------------------------------------------------------- /code/0368. Largest Divisible Subset.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: 3 | Si % Sj = 0 or Sj % Si = 0. 4 | If there are multiple solutions, return any subset is fine. 5 | */ 6 | 7 | vector largestDivisibleSubset(vector& nums) { 8 | //dp 存set个数,dp存截至该元素set最大的数目,整数倍前面值时update 9 | sort(nums.begin(),nums.end()); 10 | int n=nums.size(); 11 | vector res; 12 | if(n==0) return res; 13 | int max_element=0,max_count=1; 14 | 15 | vector path(n,-1); 16 | vector dp(n,1); 17 | for(int i=1;i=0;j--){ 19 | if(nums[i]%nums[j]==0 && dp[j]+1>dp[i]){ 20 | dp[i]=dp[j]+1; 21 | path[i]=j; 22 | } 23 | } 24 | if(dp[i]>max_count){ 25 | max_count=dp[i];max_element=i; 26 | } 27 | } 28 | for(int i=max_element;i>=0;){ 29 | res.push_back(nums[i]); 30 | i=path[i]; 31 | } 32 | return res; 33 | } 34 | -------------------------------------------------------------------------------- /code/0371. Sum of Two Integers.h: -------------------------------------------------------------------------------- 1 | /* 2 | Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 3 | 4 | Example 1: 5 | 6 | Input: a = 1, b = 2 7 | Output: 3 8 | Example 2: 9 | 10 | Input: a = -2, b = 3 11 | Output: 1 12 | */ 13 | 14 | int getSum(int a, int b) { 15 | if(!b) return a; 16 | return getSum(a^b, ((a & b) & 0x7FFFFFFF) << 1); 17 | 18 | // 1 1 1110 1100 1000 0 19 | //-1 1111 0010 0100 1000 0 20 | //负数 1111可以理解为 111减去1000, 所以 a&b 出现两个1000时一个是正的,一个是负数 21 | //用0x7fffffff 消掉最前面的。 22 | 23 | //1 0001 1111 24 | //-2 1110 0000 25 | } 26 | -------------------------------------------------------------------------------- /code/0374Guess Number Higher or Lower.h: -------------------------------------------------------------------------------- 1 | /* 2 | We are playing the Guess Game. The game is as follows: 3 | I pick a number from 1 to n. You have to guess which number I picked. 4 | Every time you guess wrong, I'll tell you whether the number is higher or lower. 5 | You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): 6 | 7 | -1 : My number is lower 8 | 1 : My number is higher 9 | 0 : Congrats! You got it! 10 | */ 11 | 12 | int guessNumber(int n) { 13 | int start=1,end=n; 14 | while(start<=end){ //n+1会OVERFLOW,所以[l,r]用等号,不是[l,r) 15 | int mid=start+(end-start)/2; 16 | int res=guess(mid); 17 | if(res==0) 18 | return mid; 19 | else if(res==-1) 20 | end=mid-1; //mid and mid-1 both OK 21 | else 22 | start=mid+1; 23 | } 24 | return -1; 25 | } 26 | -------------------------------------------------------------------------------- /code/0377. Combination Sum IV.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array with all positive numbers and no duplicates, find the number of possible combinations 3 | that add up to a positive integer target. 4 | 5 | nums = [1, 2, 3] 6 | target = 4 7 | 8 | The possible combination ways are: 9 | (1, 1, 1, 1) 10 | (1, 1, 2) 11 | (1, 2, 1) 12 | (1, 3) 13 | (2, 1, 1) 14 | (2, 2) 15 | (3, 1) 16 | Note that different sequences are counted as different combinations. 17 | */ 18 | 19 | int combinationSum4(vector& nums, int target) { 20 | int n=nums.size(); 21 | vector dp(target+1,0); 22 | dp[0]=1; 23 | for(int i=1;i=nums[j]) 26 | dp[i]+=dp[i-nums[j]]; 27 | return dp[target]; 28 | } 29 | -------------------------------------------------------------------------------- /code/0378Kth Smallest Element in a Sorted Matrix.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. 3 | Note that it is the kth smallest element in the sorted order, not the kth distinct element. 4 | 5 | Example: 6 | 7 | matrix = [ 8 | [ 1, 5, 9], 9 | [10, 11, 13], 10 | [12, 13, 15] 11 | ], 12 | k = 8, 13 | return 13. 14 | */ 15 | 16 | int helper(vector>& matrix, int target){ //返回小于等于target的个数 17 | int n=matrix.size(),m=matrix[0].size(); 18 | int i=0,j=m-1; 19 | int sum=0; 20 | while(i=0){ 21 | if(matrix[i][j]>target) 22 | j--; 23 | else{ 24 | sum+=(j+1); 25 | i++; 26 | } 27 | } 28 | return sum; 29 | } 30 | 31 | int kthSmallest(vector>& matrix, int k) { 32 | int n=matrix.size(); 33 | int m=matrix[0].size(); 34 | int start=matrix[0][0],end=matrix[n-1][m-1]+1; 35 | int mid; 36 | while(start=k) //大于等于mid时,count(mid)大于等于k 40 | end=mid; 41 | else 42 | start=mid+1; 43 | } 44 | return start; 45 | } 46 | -------------------------------------------------------------------------------- /code/0395. Longest Substring with At Least K Repeating Characters.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Find the length of the longest substring T of a given string (consists of lowercase letters only) 4 | such that every character in T appears no less than k times. 5 | 6 | Input: 7 | s = "aaabb", k = 3 8 | Output: 9 | 3 10 | 11 | Input: 12 | s = "ababbc", k = 2 13 | Output: 14 | 5 15 | */ 16 | 17 | int longestSubstring(string s, int k) { 18 | //aaabaa k=2, 种类过多有的不够k。2种 19 | //ababab k=2, 种类过少不能加入混合但。1种 20 | int n=s.size(), res=0; 21 | for(int type=1;type<=26;type++){ 22 | int start=0, count_type=0, count_k=0; 23 | vector count(26,0); 24 | for(int end=0; endtype){ 30 | count[s[start]-'a']--; 31 | if(count[s[start]-'a']==0) count_type--; 32 | if(count[s[start]-'a']==k-1) count_k--; 33 | start++; 34 | } 35 | } 36 | } 37 | return res; 38 | } 39 | -------------------------------------------------------------------------------- /code/0402. Remove K Digits.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-negative integer num represented as a string, remove k digits from the number 3 | so that the new number is the smallest possible. 4 | 5 | Note: 6 | The length of num is less than 10002 and will be ≥ k. 7 | The given num does not contain any leading zero. 8 | 9 | Input: num = "1432219", k = 3 10 | Output: "1219" 11 | */ 12 | 13 | string removeKdigits(string num, int k) { 14 | int n=num.size(), i=0; 15 | string s=""; 16 | for(;i0;i++){ 17 | if(!s.size()|| num[i]>=s.back()) s+=(num[i]); 18 | else{ 19 | while(k>0 && s.size() && s.back()>num[i]){ 20 | s.pop_back(); 21 | k--; 22 | } 23 | s+=(num[i]); 24 | } 25 | } 26 | 27 | if(i& nums) { 15 | //2^N > sum*N dfs 超时 16 | int sum=0; 17 | for(auto i:nums) 18 | sum+=i; 19 | if(sum%2==1) return false; 20 | sum/=2; 21 | vector dp(sum+1,false); 22 | dp[0]=true; 23 | for(auto i:nums){ 24 | //从后往前************** 25 | for(int j=sum-i;j>=0;j--) 26 | if(dp[j]) 27 | dp[j+i]=true; 28 | if(dp[sum]) return true; 29 | } 30 | return dp[sum]; 31 | } 32 | -------------------------------------------------------------------------------- /code/0429. N-ary Tree Level Order Traversal.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 | */ 4 | vector> levelOrder(Node* root) { 5 | vector> res; 6 | int level=0; 7 | queue q; 8 | if(root) q.push(root); 9 | while(!q.empty()){ 10 | int k=q.size(); 11 | res.push_back({}); 12 | for(int i=0;ival); 16 | for(auto i: cur->children) 17 | if(i) 18 | q.push(i); 19 | } 20 | level++; 21 | } 22 | return res; 23 | } 24 | -------------------------------------------------------------------------------- /code/0435. Non-overlapping Intervals.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of intervals, find the minimum number of intervals you need to remove 3 | to make the rest of the intervals non-overlapping. 4 | 5 | You may assume the interval's end point is always bigger than its start point. 6 | Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. 7 | 8 | Input: [ [1,2], [2,3], [3,4], [1,3] ] 9 | Output: 1 10 | */ 11 | 12 | int eraseOverlapIntervals(vector>& intervals) { 13 | sort(intervals.begin(),intervals.end()); 14 | int i=0,j=1,res=0; 15 | while(j0){ //已经排序了,第一个肯定小 17 | if(intervals[j][0] 3 25 | 2. 5 -> 2 -> 1 26 | 3. -3 -> 11 27 | */ 28 | 29 | class Solution { 30 | private: 31 | void helper(int &res,TreeNode* root, int sum, int target){ 32 | sum+=root->val; 33 | if(sum==target) 34 | res++; 35 | if(root->left) 36 | helper(res,root->left,sum,target); 37 | if(root->right) 38 | helper(res,root->right,sum,target); 39 | return; 40 | } 41 | public: 42 | int pathSum(TreeNode* root, int sum) { 43 | if(!root) return 0; 44 | int res=0; 45 | helper(res,root,0,sum); 46 | res+=pathSum(root->left,sum); 47 | res+=pathSum(root->right,sum); 48 | return res; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /code/0441Arranging Coins.h: -------------------------------------------------------------------------------- 1 | /* 2 | You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. 3 | Given n, find the total number of full staircase rows that can be formed. 4 | n is a non-negative integer and fits within the range of a 32-bit signed integer. 5 | 6 | n = 5 7 | The coins can form the following rows: 8 | ¤ 9 | ¤ ¤ 10 | ¤ ¤ 11 | Because the 3rd row is incomplete, we return 2. 12 | 13 | n = 8 14 | The coins can form the following rows: 15 | ¤ 16 | ¤ ¤ 17 | ¤ ¤ ¤ 18 | ¤ ¤ 19 | Because the 4th row is incomplete, we return 3. 20 | */ 21 | 22 | int arrangeCoins(int n) { 23 | if(n<=1) return n; 24 | long long m=n; 25 | int l=1,r=sqrt(2*m)+1,mid; //不能从n开始,sum会越界 26 | while(ln) r=mid; 34 | else l=mid+1; 35 | } 36 | return l-1; 37 | } 38 | -------------------------------------------------------------------------------- /code/0452. Minimum Number of Arrows to Burst Balloons.h: -------------------------------------------------------------------------------- 1 | /* 2 | There are a number of spherical balloons spread in two-dimensional space. 3 | For each balloon, provided input is the start and end coordinates of the horizontal diameter. 4 | Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. 5 | Start is always smaller than end. There will be at most 104 balloons. 6 | 7 | An arrow can be shot up exactly vertically from different points along the x-axis. 8 | A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. 9 | There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. 10 | The problem is to find the minimum number of arrows that must be shot to burst all balloons. 11 | 12 | Input: 13 | [[10,16], [2,8], [1,6], [7,12]] 14 | 15 | Output: 16 | 2 17 | */ 18 | int findMinArrowShots(vector>& points) { 19 | sort(points.begin(),points.end()); 20 | int prev=INT_MIN,res=0; 21 | for(int i=0;iprev){ //[INT_MIN, INT_MAX] 23 | prev=points[i][1]; 24 | res++; 25 | } 26 | else if(points[i][1]& nums) { 14 | int n=nums.size(), res=0; 15 | if(n<=1) return 0; 16 | while(true){ 17 | int zero=0,count_0=0,count_1=0; 18 | for(int i=0;i>1; 22 | if(!nums[i]) zero++; 23 | } 24 | res+=count_0*count_1; 25 | if(zero==n) break; 26 | } 27 | return res; 28 | } 29 | -------------------------------------------------------------------------------- /code/0487. Max Consecutive Ones II.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0. 3 | 4 | Input: [1,0,1,1,0] 5 | Output: 4 6 | 7 | Follow up: 8 | What if the input numbers come in one by one as an infinite stream? In other words, 9 | you can't store all numbers coming from the stream as it's too large to hold in memory. 10 | Could you solve it efficiently? 11 | */ 12 | 13 | int findMaxConsecutiveOnes(vector& A) { 14 | int K=1; 15 | vector res(K+1,0); 16 | int n=A.size(),ma=0; 17 | if(K>=n) return n; 18 | for(int i=0;i=1;j--) 25 | res[j]=res[j-1]+1; 26 | res[0]=0; 27 | } 28 | ma=max(ma,res[K]); 29 | } 30 | return ma; 31 | } 32 | -------------------------------------------------------------------------------- /code/0493. Reverse Pairs.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j]. 3 | You need to return the number of important reverse pairs in the given array. 4 | 5 | Input: [1,3,2,3,1] 6 | Output: 2 7 | 8 | Input: [2,4,3,5,1] 9 | Output: 3 10 | */ 11 | 12 | class Solution { 13 | private: 14 | int mergesort(vector& nums,int l,int r){ 15 | if(r-l<=1) return 0; 16 | int mid=l+(r-l)/2,count=0; 17 | count+=mergesort(nums,l,mid); 18 | count+=mergesort(nums,mid,r); 19 | int jj=mid; 20 | for(int ii=l;ii(long)2*(nums[jj])) jj++; 22 | count+=(jj-mid); 23 | } 24 | inplace_merge(nums.begin()+l,nums.begin()+mid,nums.begin()+r); 25 | return count; 26 | } 27 | public: 28 | int reversePairs(vector& nums) { 29 | return mergesort(nums,0,nums.size()); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /code/0498. Diagonal Traverse.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a matrix of M x N elements (M rows, N columns), 3 | return all elements of the matrix in diagonal order as shown in the below image. 4 | 5 | Input: 6 | [ 7 | [ 1, 2, 3 ], 8 | [ 4, 5, 6 ], 9 | [ 7, 8, 9 ] 10 | ] 11 | 12 | Output: [1,2,4,7,5,3,6,8,9] 13 | */ 14 | 15 | vector findDiagonalOrder(vector>& matrix) { 16 | // 00 01 02 03 17 | // 10 11 12 13 18 | // 20 21 22 23 19 | int n=matrix.size(); 20 | vector res; 21 | if(!n) return res; 22 | int m=matrix[0].size(); 23 | for(int i=0;i=0 && i-j=0 && i-j nextGreaterElements(vector& nums) { 11 | //O(N) 12 | int n=nums.size(); 13 | vector res(n,-1); 14 | stack s; 15 | 16 | for(int i=0;inums[s.top()]){ 21 | res[s.top()]=nums[i]; 22 | s.pop(); 23 | } 24 | s.push(i); 25 | } 26 | } 27 | 28 | for(int i=0;inums[s.top()]) 31 | while( nums[i]>nums[s.top()]){ 32 | res[s.top()]=nums[i]; 33 | s.pop(); 34 | } 35 | } 36 | return res; 37 | } 38 | -------------------------------------------------------------------------------- /code/0516Longest Palindromic Subsequence.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, find the longest palindromic subsequence's length in s. 3 | You may assume that the maximum length of s is 1000. 4 | Example 1: 5 | Input: 6 | "bbbab" 7 | Output: 8 | 4 9 | One possible longest palindromic subsequence is "bbbb". 10 | */ 11 | 12 | int longestPalindromeSubseq(string s) { 13 | //可以不是连续的 14 | int n=s.size(); 15 | vector> dp(n+1, vector(n+1,0)); 16 | for(int i=1;i& coins) { 16 | // amount=5:1, 2, 5 17 | // 0 1 2 3 4 5 18 | //5:0 0 0 0 0 1 19 | //2:0 0 1 0 1 0 20 | //1 0 1 2 2 3 4 21 | 22 | //过k次amount,免去重复的。 23 | vector dp(amount+1,0); 24 | dp[0]=1; 25 | int n=coins.size(); 26 | for(int i=0;i=coins[i]) dp[coins[i]]=1; // 通过设dp[0]=1 免去这步 28 | for(int j=coins[i];j& nums) { 12 | // 1 1 1 0 1 0 0 1 13 | // 1 2 3 2 3 2 1 2 14 | unordered_map m; 15 | m[0]=-1; 16 | int n=nums.size(),res=0,cur=0; 17 | for(int i=0;i lTos,sTol; 12 | string s="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 13 | public: 14 | // Encodes a URL to a shortened URL. 15 | string encode(string longUrl) { 16 | if(lTos.count(longUrl)) return lTos[longUrl]; 17 | string shortUrl=""; 18 | while(shortUrl==""){ 19 | // collision 20 | string res; 21 | for(int i=0;i<6;i++){ 22 | res+=rand()%s.size(); 23 | } 24 | if(!sTol.count(res)){ 25 | lTos[longUrl]=res; 26 | sTol[res]=longUrl; 27 | shortUrl=res; 28 | } 29 | } 30 | return shortUrl; 31 | } 32 | 33 | // Decodes a shortened URL to its original URL. 34 | string decode(string shortUrl) { 35 | //假设一定有 36 | return sTol[shortUrl]; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /code/0540. Single Element in a Sorted Array.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array consisting of only integers where every element appears exactly twice 3 | except for one element which appears exactly once. Find this single element that appears only once. 4 | */ 5 | 6 | int singleNonDuplicate(vector& nums) { 7 | int l=0,r=nums.size()-1,mid; 8 | while(l<=r){ 9 | mid=l+(r-l)/2; 10 | if(l==r || (nums[mid]!=nums[mid-1] && nums[mid]!=nums[mid+1] )) return nums[mid]; 11 | if(nums[mid]==nums[mid-1]){ 12 | //[3,3,7,7,10,11,11] 13 | if((mid-l)%2) l=mid+1; 14 | //[1,1,2,3,3,4,4,8,8] 15 | else r=mid; 16 | } 17 | else{ 18 | //[3,3,5, 7,7,11,11] 19 | if((mid-l)%2) r=mid-1; 20 | //[1,1,3,3,4,4,5,8,8] 21 | else l=mid; 22 | } 23 | } 24 | return nums[mid]; 25 | } 26 | -------------------------------------------------------------------------------- /code/0548. Split Array with Equal Sum.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies following conditions: 3 | 4 | 0 < i, i + 1 < j, j + 1 < k < n - 1 5 | Sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) should be equal. 6 | where we define that subarray (L, R) represents a slice of the original array starting from the element indexed L to the element indexed R. 7 | 8 | 9 | Input: [1,2,1,2,1,2,1] 10 | Output: True 11 | 12 | i = 1, j = 3, k = 5. 13 | 14 | 1 <= n <= 2000. 15 | Elements in the given array will be in range [-1,000,000, 1,000,000]. 16 | */ 17 | 18 | bool splitArray(vector& nums) { 19 | // 1 2 1 2 1 2 1 20 | // 1 3 4 6 7 9 10 21 | vector sum=nums; 22 | int n=nums.size(); 23 | for(int i=1;i> m; 26 | for(int i=1;i=4){ 31 | for(int k=j+2;k<=i-2;k++){ 32 | if(sum[k-1]-sum[j]==sum[i-1]-sum[k]) 33 | return true; 34 | } 35 | } 36 | } 37 | } 38 | } 39 | return false; 40 | } 41 | -------------------------------------------------------------------------------- /code/0560. Subarray Sum Equals K.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 3 | 4 | Example 1: 5 | Input:nums = [1,1,1], k = 2 6 | Output: 2 7 | Note: 8 | The length of the array is in range [1, 20,000]. 9 | The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 10 | */ 11 | 12 | int subarraySum(vector& nums, int k) { 13 | //可以是负数,不能two pointer 14 | //在hash map 找 sum-k 15 | int sum=0,res=0; 16 | 17 | unordered_map data; 18 | //data[0]=1; //从第一个开始 19 | for(auto i:nums){ 20 | sum+=i; 21 | if(sum==k) //或者开始加入0 22 | res++; 23 | if(data.count(sum-k)) 24 | res+=data[sum-k]; 25 | data[sum]++; 26 | } 27 | return res; 28 | } 29 | -------------------------------------------------------------------------------- /code/0572. Subtree of Another Tree.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. 3 | A subtree of s is a tree consists of a node in s and all of this node's descendants. 4 | The tree s could also be considered as a subtree of itself. 5 | 6 | Given tree s: 7 | 3 8 | / \ 9 | 4 5 10 | / \ 11 | 1 2 12 | Given tree t: 13 | 4 14 | / \ 15 | 1 2 16 | Return true, because t has the same structure and node values with a subtree of s. 17 | */ 18 | 19 | class Solution { 20 | public: 21 | //判断是否相同 22 | bool helper(TreeNode* s, TreeNode* t){ 23 | if(!s && !t) 24 | return true; 25 | if(s!=NULL && t!=NULL &&(s->val==t->val)) 26 | return helper(s->left,t->left)&&helper(s->right,t->right); 27 | return false; 28 | 29 | } 30 | bool isSubtree(TreeNode* s, TreeNode* t) { 31 | if(helper(s,t)) return true; 32 | if((s->left) && isSubtree(s->left,t)) 33 | return true; 34 | if((s->right) && isSubtree(s->right,t)) 35 | return true; 36 | return false; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /code/0576. Out of Boundary Paths.h: -------------------------------------------------------------------------------- 1 | /* 2 | There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, 3 | you can move the ball to adjacent cell or cross the grid boundary in four directions (up, down, left, right). 4 | However, you can at most move N times. Find out the number of paths to move the ball out of grid boundary. 5 | The answer may be very large, return it after mod 109 + 7. 6 | 7 | Input: m = 2, n = 2, N = 2, i = 0, j = 0 8 | Output: 6 9 | */ 10 | 11 | int findPaths(int m, int n, int N, int i, int j) { 12 | if(N<=0) return 0; 13 | vector move={0,-1,0,1,0}; 14 | vector> prev(m,vector(n,0)); 15 | prev[i][j]=1; 16 | int res=0; 17 | for(int step=1;step<=N;step++){ 18 | vector> cur(m,vector(n,0)); 19 | for(int row=0;row=m || y<0 || y>=n) 25 | res=(res+prev[row][col])%1000000007; 26 | else 27 | cur[x][y]=(cur[x][y]+prev[row][col])%1000000007; 28 | } 29 | } 30 | prev=cur; 31 | } 32 | return res; 33 | } 34 | -------------------------------------------------------------------------------- /code/0583Delete Operation for Two Strings.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, 3 | where in each step you can delete one character in either string. 4 | 5 | Example 1: 6 | Input: "sea", "eat" 7 | Output: 2 8 | Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". 9 | */ 10 | int minDistance(string word1, string word2) { 11 | //dp[i][j]=min(dp[i-1][j],dp[i][j-1])+1; 在这种情况不需要2d,只需要两个vector 12 | int n=word1.size(),m=word2.size(); 13 | if(n==0 || m==0) return m+n; 14 | vector prev(m+1,0); 15 | vector cur(m+1,0); 16 | 17 | //初始化第一行 18 | for(int i=0;i postorder(Node* root) { 7 | Node* cur=root; 8 | vector res; 9 | stack s; 10 | while(cur || !s.empty()){ 11 | if(cur){ 12 | res.push_back(cur->val); 13 | for(auto i: cur->children) 14 | if(i) 15 | s.push(i); 16 | cur=NULL; 17 | } 18 | else{ 19 | cur=s.top(); 20 | s.pop(); 21 | } 22 | } 23 | reverse(res.begin(),res.end()); 24 | return res; 25 | } 26 | -------------------------------------------------------------------------------- /code/0634. Find the Derangement of An Array.h: -------------------------------------------------------------------------------- 1 | /* 2 | In combinatorial mathematics, a derangement is a permutation of the elements of a set, 3 | such that no element appears in its original position. 4 | 5 | There's originally an array consisting of n integers from 1 to n in ascending order, 6 | you need to find the number of derangement it can generate. 7 | 8 | Also, since the answer may be very large, you should return the output mod 10^9 + 7. 9 | 10 | Input: 3 11 | Output: 2 12 | Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2]. 13 | Note: 14 | n is in the range of [1, 10^6]. 15 | */ 16 | 17 | int findDerangement(int n) { 18 | //dp[n]=(n-1)*(dp[n-2]+dp[n-1]); 19 | // 第一个位置n-1个选择,假设放了i 20 | //第i个位置放1,then dp[n-2] 21 | //第i个位置不放1,then 从第二个元素开始,第i个不放1,其他不放本身,dp[n-1] 22 | if(n<=3) return n-1; 23 | 24 | int M = 1000000007; 25 | long a1=1,a2=2; 26 | 27 | for(int i=4;i<=n;i++){ 28 | int temp=a2; 29 | a2=(long(i-1)*(a1+a2))%M; 30 | a1=temp; 31 | } 32 | return (int)a2; 33 | } 34 | -------------------------------------------------------------------------------- /code/0650_2 Keys Keyboard.h: -------------------------------------------------------------------------------- 1 | /* 2 | Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step: 3 | Copy All: You can copy all the characters present on the notepad (partial copy is not allowed). 4 | Paste: You can paste the characters which are copied last time. 5 | Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. 6 | Output the minimum number of steps to get n 'A'. 7 | */ 8 | 9 | int minSteps(int n) { 10 | //必须能整除 11 | //3 1 1 1 12 | //4 2*2 13 | //5 1 1 1 1 1 14 | //6 3*2 15 | //8 2*2*2 16 | //10 2*5 2+5 or 5*2 5+2 17 | int ans=0; 18 | while(n!=1){ 19 | for(int i=2;i<=n;i++){ 20 | if(n%i==0){ 21 | ans+=i; 22 | n/=i; 23 | break; 24 | } 25 | } 26 | } 27 | return ans; 28 | } 29 | -------------------------------------------------------------------------------- /code/0662. Maximum Width of Binary Tree.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, write a function to get the maximum width of the given tree. 3 | The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, 4 | but some nodes are null. 5 | 6 | The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, 7 | where the null nodes between the end-nodes are also counted into the length calculation. 8 | 9 | 1 10 | / \ 11 | 3 2 12 | / \ \ 13 | 5 3 9 14 | 15 | Output: 4 16 | */ 17 | 18 | int widthOfBinaryTree(TreeNode* root) { 19 | vector> q; 20 | int res=0; 21 | if(!root) return 0; 22 | q.push_back({root,0}); 23 | while(q.size()){ 24 | int k=q.size(); 25 | vector> temp; 26 | res=max(res,q.back().second-q.front().second); 27 | for(int i=0;ileft) 29 | temp.push_back({q[i].first->left,q[i].second*2+1}); 30 | if(q[i].first->right) 31 | temp.push_back({q[i].first->right,q[i].second*2+2}); 32 | } 33 | q=temp; 34 | //如果不减小,层数很多时候会越界 35 | for(int i=q.size()-1;i>=0;i--) 36 | q[i].second-=q[0].second; 37 | } 38 | return res+1; 39 | } 40 | -------------------------------------------------------------------------------- /code/0673. Number of Longest Increasing Subsequence.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted array of integers, find the number of longest increasing subsequence. 3 | 4 | Input: [1,3,5,4,7] 5 | Output: 2 6 | Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. 7 | */ 8 | 9 | int findNumberOfLIS(vector& nums) { 10 | //dp O(N^2) 11 | // 1 2 4 3 5 4 7 2 12 | //pos 1 2 3 3 4 4 5 2 13 | //counts 1 1 1 1 2 1 3 1 14 | int n=nums.size(); 15 | vector pos(n,0); 16 | vector counts(n,0); 17 | for(int i=0;inums[j]){ 20 | if(pos[i]length){ 37 | length=pos[i]; 38 | res=counts[i]; 39 | } 40 | //并列位置是最后一个 41 | else if(pos[i]==length){ 42 | res+=counts[i]; 43 | } 44 | } 45 | return res; 46 | } 47 | -------------------------------------------------------------------------------- /code/0701. Insert into a Binary Search Tree.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given the root node of a binary search tree (BST) and a value to be inserted into the tree, 3 | insert the value into the BST. Return the root node of the BST after the insertion. 4 | It is guaranteed that the new value does not exist in the original BST. 5 | 6 | Note that there may exist multiple valid ways for the insertion, 7 | as long as the tree remains a BST after insertion. You can return any of them. 8 | 9 | Given the tree: 10 | 4 11 | / \ 12 | 2 7 13 | / \ 14 | 1 3 15 | And the value to insert: 5 16 | You can return this binary search tree: 17 | 4 18 | / \ 19 | 2 7 20 | / \ / 21 | 1 3 5 22 | This tree is also valid: 23 | 5 24 | / \ 25 | 2 7 26 | / \ 27 | 1 3 28 | \ 29 | 4 30 | */ 31 | 32 | TreeNode* insertIntoBST(TreeNode* &root, int val) { 33 | if(!root) 34 | root =new TreeNode(val); 35 | else if(root->val>val) 36 | insertIntoBST(root->left,val); 37 | else 38 | insertIntoBST(root->right,val); 39 | return root; 40 | } 41 | -------------------------------------------------------------------------------- /code/0704Binary Search.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted (in ascending order) integer array nums of n elements and a target value, 3 | write a function to search target in nums. If target exists, then return its index, otherwise return -1. 4 | */ 5 | 6 | int search(vector& nums, int target) { 7 | int n=nums.size(); 8 | int left=0,right=n,mid; 9 | while(lefttarget) 14 | right=mid; 15 | else 16 | left=mid+1; 17 | } 18 | return -1; 19 | } 20 | -------------------------------------------------------------------------------- /code/0718Maximum Length of Repeated Subarray.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays. 3 | 4 | Example 1: 5 | Input: 6 | A: [1,2,3,2,1] 7 | B: [3,2,1,4,7] 8 | Output: 3 9 | Explanation: 10 | The repeated subarray with maximum length is [3, 2, 1]. 11 | */ 12 | int findLength(vector& A, vector& B) { 13 | //dp,dp[i+1][j+1]=dp[i][j]+1; 14 | //must be continuous, because 0 if not equal 15 | int n=A.size(),m=B.size(); 16 | int res=0; 17 | vector> dp(n+1,vector(m+1,0)); 18 | for(int i=0;i& words) { 16 | sort(words.begin(),words.end()); 17 | unordered_set s; 18 | s.insert(""); 19 | string res=""; 20 | for(int i=0;ires.size()) 24 | res=words[i]; 25 | } 26 | return res; 27 | } 28 | -------------------------------------------------------------------------------- /code/0727. Minimum Window Subsequence.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W. 3 | 4 | If there is no such window in S that covers all characters in T, return the empty string "". 5 | If there are multiple such minimum-length windows, return the one with the left-most starting index. 6 | 7 | Input: 8 | S = "abcdebdde", T = "bde" 9 | Output: "bcde" 10 | 11 | Note: 12 | All the strings in the input will only contain lowercase letters. 13 | The length of S will be in the range [1, 20000]. 14 | The length of T will be in the range [1, 100]. 15 | */ 16 | string minWindow(string S, string T) { 17 | // dbcdebde 18 | // 012345678 19 | //bxx1111555 20 | //dxxxx11155 21 | //exxxxx1115 22 | int n=S.size(),m=T.size(),res=INT_MAX; 23 | string s=""; 24 | vector> dp(m+1,vector(n+1,-1)); 25 | for(int i=0;i dailyTemperatures(vector& temperatures) { 14 | int n=temperatures.size(); 15 | vector res(n,0); 16 | stack data; 17 | for(int i=0;i0 && temperatures[data.top()]& nums) { 18 | //错了,是must not delete any 19 | int n=nums.size(); 20 | vector result(n); 21 | result[1]=nums[1]; 22 | result[2]=max(nums[1],nums[2]); 23 | for(int i=3;i& nums) { 30 | vector sum(10001,0); 31 | for(auto i:nums) 32 | sum[i]+=i; 33 | return rob(sum); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /code/0768. Max Chunks To Make Sorted II.h: -------------------------------------------------------------------------------- 1 | /* 2 | This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, 3 | the input array could be up to length 2000, and the elements could be up to 10**8. 4 | 5 | Given an array arr of integers (not necessarily distinct), we split the array into some number of "chunks" (partitions), 6 | and individually sort each chunk. After concatenating them, the result equals the sorted array. 7 | 8 | What is the most number of chunks we could have made? 9 | 10 | Input: arr = [5,4,3,2,1] 11 | Output: 1 12 | 13 | Input: arr = [2,1,3,4,4] 14 | Output: 4 15 | */ 16 | 17 | int maxChunksToSorted(vector& arr) { 18 | //3 2 2 1 3 1 3 4 19 | //1 1 2 2 3 3 3 4 20 | int n=arr.size(),res=0; 21 | long long sum1=0,sum2=0; 22 | vector s=arr; 23 | sort(s.begin(),s.end()); 24 | for(int i=0;i& arr) { 16 | int n=arr.size(),res=0,longest=-1; 17 | for(int i=0;ilongest){ 19 | res++; 20 | longest=arr[i]; 21 | } 22 | else 23 | longest=max(longest,arr[i]); 24 | } 25 | return res; 26 | } 27 | -------------------------------------------------------------------------------- /code/0783. Minimum Distance Between BST Nodes.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a Binary Search Tree (BST) with the root node root, 3 | return the minimum difference between the values of any two different nodes in the tree. 4 | 5 | Input: root = [4,2,6,1,3,null,null] 6 | Output: 1 7 | The given tree [4,2,6,1,3,null,null] is represented by the following diagram: 8 | 9 | 4 10 | / \ 11 | 2 6 12 | / \ 13 | 1 3 14 | 15 | while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2. 16 | The size of the BST will be between 2 and 100. 17 | The BST is always valid, each node's value is an integer, and each node's value is different. 18 | */ 19 | 20 | class Solution { 21 | private: 22 | long res=INT_MAX; 23 | void diff(TreeNode* root,TreeNode* &prev){ 24 | if(!root) return; 25 | diff(root->left,prev); 26 | if(prev) //not first time 27 | res=min(res,(long)root->val-prev->val); 28 | prev=root; 29 | diff(root->right,prev); 30 | return; 31 | } 32 | public: 33 | int minDiffInBST(TreeNode* root) { 34 | TreeNode *prev=NULL; 35 | diff(root, prev); 36 | return (int)res; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /code/0790. Domino and Tromino Tiling.h: -------------------------------------------------------------------------------- 1 | /* 2 | We have two types of tiles: a 2x1 domino shape, and an "L" tromino shape. These shapes may be rotated. 3 | XX <- domino 4 | 5 | XX <- "L" tromino 6 | X 7 | Given N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 7. 8 | (In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells 9 | on the board such that exactly one of the tilings has both squares occupied by a tile.) 10 | 11 | Example: 12 | Input: 3 13 | Output: 5 14 | Explanation: 15 | The five different ways are listed below, different letters indicates different tiles: 16 | XYZ XXZ XYY XXY XYY 17 | XYZ YYZ XZZ XYY XXY 18 | */ 19 | 20 | int numTilings(int N) { 21 | //half fill and fill state 22 | //0 1 1 23 | //0 0 2 24 | if(N<=2) return N; 25 | vector> dp(2,vector(N+1,0)); 26 | dp[0][1]=1;dp[0][2]=2; 27 | dp[1][2]=2; //2nd col half filled 28 | for(int i=3;i& words) { 11 | int n=S.size(),res=0; 12 | vector> data(26,vector()); 13 | for(int i=0;i& A, int K) { 15 | //dp[k][n] A 中0到n分成K份 16 | int n=A.size(); 17 | vector sum(n,A[0]*1.0); 18 | for(int i=1;i> dp(K+1,vector(n,INT_MIN*1.0)); 21 | for(int i=0;ileft),right=helper(root->right); 18 | int res=left+right+(root->val); 19 | if(!res) root=NULL; 20 | return res; 21 | } 22 | public: 23 | TreeNode* pruneTree(TreeNode* root) { 24 | helper(root); 25 | return root; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /code/0825. Friends Of Appropriate Ages.h: -------------------------------------------------------------------------------- 1 | /* 2 | Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person. 3 | Person A will NOT friend request person B (B != A) if any of the following conditions are true: 4 | 5 | age[B] <= 0.5 * age[A] + 7 6 | age[B] > age[A] 7 | age[B] > 100 && age[A] < 100 8 | Otherwise, A will friend request B. 9 | 10 | Note that if A requests B, B does not necessarily request A. Also, people will not friend request themselves. 11 | How many total friend requests are made? 12 | 13 | Input: [16,16] 14 | Output: 2 15 | Explanation: 2 people friend request each other. 16 | 17 | Input: [16,17,18] 18 | Output: 2 19 | Explanation: Friend requests are made 17 -> 16, 18 -> 17. 20 | 21 | Input: [20,30,100,110,120] 22 | Output: 23 | Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. 24 | 25 | Notes: 26 | 1 <= ages.length <= 20000. 27 | 1 <= ages[i] <= 120. 28 | */ 29 | 30 | int numFriendRequests(vector& ages) { 31 | //没有必要sort or map,年龄数字小 32 | vector count(121,0); 33 | int res=0; 34 | for(auto i:ages) 35 | count[i]++; 36 | // 向小于等于自己年龄的发request, sliding sum 37 | for(int i=1;i<=120;i++){ 38 | for(int j=0.5*i+8;j<=i;j++){ 39 | if(i==j) res+=count[i]*(count[i]-1); 40 | else res+=count[j]*count[i]; 41 | } 42 | } 43 | return res; 44 | } 45 | -------------------------------------------------------------------------------- /code/0836. Rectangle Overlap: -------------------------------------------------------------------------------- 1 | /* 2 | A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, 3 | and (x2, y2) are the coordinates of its top-right corner. 4 | 5 | Two rectangles overlap if the area of their intersection is positive. To be clear, 6 | two rectangles that only touch at the corner or edges do not overlap. 7 | 8 | Given two (axis-aligned) rectangles, return whether they overlap. 9 | 10 | Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] 11 | Output: true 12 | 13 | Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] 14 | Output: false 15 | */ 16 | 17 | bool isRectangleOverlap(vector& rec1, vector& rec2) { 18 | return rec1[0]>& rectangles) { 11 | set x,y; 12 | for(auto i: rectangles){ 13 | x.insert(i[0]),x.insert(i[2]), 14 | y.insert(i[1]),y.insert(i[3]); 15 | } 16 | vector xx(x.begin(),x.end()),yy(y.begin(),y.end()); 17 | int res=0; 18 | vector> data(xx.size()+1,vector(yy.size()+1,0)); 19 | for(auto i:rectangles) 20 | for(int j=lower_bound(xx.begin(),xx.end(),i[0])-xx.begin();xx[j]!=i[2];j++) 21 | for(int k=lower_bound(yy.begin(),yy.end(),i[1])-yy.begin();yy[k]!=i[3];k++) 22 | if((data[j][k]++)==0) 23 | res=(res+((long long)(xx[j+1]-xx[j]))*(yy[k+1]-yy[k]))%1000000007; 24 | 25 | return res; 26 | } 27 | -------------------------------------------------------------------------------- /code/0862. Shortest Subarray with Sum at Least K.h: -------------------------------------------------------------------------------- 1 | /* 2 | Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. 3 | If there is no non-empty subarray with sum at least K, return -1. 4 | 5 | Input: A = [1], K = 1 6 | Output: 1 7 | 8 | Input: A = [1,2], K = 4 9 | Output: -1 10 | 11 | Input: A = [2,-1,2], K = 3 12 | Output: 3 13 | 14 | Note: 15 | 16 | 1 <= A.length <= 50000 17 | -10 ^ 5 <= A[i] <= 10 ^ 5 18 | 1 <= K <= 10 ^ 9 19 | */ 20 | 21 | int shortestSubarray(vector& A, int K) { 22 | int n=A.size(), res=INT_MAX; 23 | deque dq; 24 | vector sum(n+1,0); 25 | for(int i=0;i= K) 29 | //cur-dq里面的,当前是最短的 30 | res=min(res,i-dq.front()),dq.pop_front(); 31 | while(dq.size() && sum[dq.back()] >= sum[i]) 32 | //dq后面的-dq里面的,现在最短 33 | dq.pop_back(); 34 | dq.push_back(i); 35 | } 36 | return res==INT_MAX?-1:res; 37 | } 38 | -------------------------------------------------------------------------------- /code/0872. Leaf-Similar Trees.h: -------------------------------------------------------------------------------- 1 | /* 2 | Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence. 3 | For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). 4 | Two binary trees are considered leaf-similar if their leaf value sequence is the same. 5 | Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. 6 | */ 7 | 8 | class Solution { 9 | private: 10 | int dfs(stack &s){ 11 | while(true){ 12 | TreeNode* t=s.top(); 13 | s.pop(); 14 | if(t->right) s.push(t->right); 15 | if(t->left) s.push(t->left); 16 | if(!t->left && !t->right) return t->val; 17 | } 18 | } 19 | public: 20 | bool leafSimilar(TreeNode* root1, TreeNode* root2) { 21 | //如果直接比较array,space O(N), use stack log(N) 22 | stack s1,s2; 23 | s1.push(root1); 24 | s2.push(root2); 25 | while(!s1.empty() && !s2.empty()) 26 | if(dfs(s1)!=dfs(s2)) 27 | return false; 28 | return s1.empty()&&s2.empty(); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /code/0875Koko Eating Bananas.h: -------------------------------------------------------------------------------- 1 | /* 2 | Koko loves to eat bananas. There are N piles of bananas, the i-th pile has piles[i] bananas. 3 | The guards have gone and will come back in H hours. 4 | 5 | Koko can decide her bananas-per-hour eating speed of K. Each hour, she chooses some pile of bananas, 6 | and eats K bananas from that pile. If the pile has less than K bananas, she eats all of them instead, 7 | and won't eat any more bananas during this hour. 8 | 9 | Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. 10 | 11 | Return the minimum integer K such that she can eat all the bananas within H hours. 12 | 13 | Input: piles = [3,6,7,11], H = 8 14 | Output: 4 15 | 16 | Input: piles = [30,11,23,4,20], H = 5 17 | Output: 30 18 | 19 | Input: piles = [30,11,23,4,20], H = 6 20 | Output: 23 21 | */ 22 | 23 | int minEatingSpeed(vector& piles, int H) { 24 | int left=1,right=10e9,mid; 25 | while(left& piles) { 15 | /* 16 | return true; //Alex can choose all odd or all even; 17 | */ 18 | int n=piles.size(); 19 | //dp是score的差值 20 | vector> dp(n,vector(n,0)); 21 | for(int i=0;i0; 29 | } 30 | -------------------------------------------------------------------------------- /code/0889. Construct Binary Tree from Preorder and Postorder Traversal.h: -------------------------------------------------------------------------------- 1 | /* 2 | Return any binary tree that matches the given preorder and postorder traversals. 3 | Values in the traversals pre and post are distinct positive integers. 4 | 5 | Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1] 6 | Output: [1,2,3,4,5,6,7] 7 | 8 | Note: 9 | 1 <= pre.length == post.length <= 30 10 | pre[] and post[] are both permutations of 1, 2, ..., pre.length. 11 | It is guaranteed an answer exists. If there exists multiple answers, you can return any of them. 12 | */ 13 | 14 | TreeNode* constructFromPrePost(vector& pre, vector& post) { 15 | int i=0; 16 | stack s; 17 | for(int j=0;jval!=post[j]){ 19 | TreeNode* t=new TreeNode(pre[i++]); 20 | s.push(t); 21 | } 22 | TreeNode* temp=s.top(); 23 | s.pop(); 24 | if(s.empty()) return temp; 25 | if(!s.top()->left) 26 | s.top()->left=temp; 27 | else 28 | s.top()->right=temp; 29 | } 30 | return NULL; 31 | } 32 | -------------------------------------------------------------------------------- /code/0901. Online Stock Span.h: -------------------------------------------------------------------------------- 1 | /* 2 | Write a class StockSpanner which collects daily price quotes for some stock, 3 | and returns the span of that stock's price for the current day. 4 | 5 | The span of the stock's price today is defined as the maximum number of consecutive days 6 | (starting from today and going backwards) for which the price of the stock was less than or equal to today's price. 7 | 8 | For example, if the price of a stock over the next 7 days were [100, 80, 60, 70, 60, 75, 85], 9 | then the stock spans would be [1, 1, 1, 2, 1, 4, 6]. 10 | */ 11 | 12 | class StockSpanner { 13 | private: 14 | stack> s; 15 | int count; 16 | public: 17 | StockSpanner() { 18 | s.push({INT_MAX, -1}); 19 | count=0; 20 | } 21 | //单调减 22 | int next(int price) { 23 | while(price>=s.top().first) s.pop(); 24 | int res=count-s.top().second; 25 | s.push({price,count++}); 26 | return res; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /code/0907. Sum of Subarray Minimums.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A. 3 | 4 | Since the answer may be large, return the answer modulo 10^9 + 7. 5 | 6 | Input: [3,1,2,4] 7 | Output: 17 8 | Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. 9 | Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17. 10 | */ 11 | 12 | int sumSubarrayMins(vector& A) { 13 | int n=A.size(),res=0, mod = 1e9 + 7; 14 | vector prevSmaller(n,0); 15 | stack s1; 16 | //单调增 17 | for(int i=0;i=A[i]) 19 | s1.pop(); 20 | prevSmaller[i]=(s1.empty()?-1:s1.top()); 21 | s1.push(i); 22 | } 23 | vector sum(n,0); 24 | for(int i=0;i0) count--; 35 | else res++; 36 | } 37 | return res; 38 | } 39 | public: 40 | int minAddToMakeValid(string S) { 41 | int res=helper(S,"()"); 42 | reverse(S.begin(),S.end()); 43 | res+=helper(S,")("); 44 | return res; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /code/0935. Knight Dialer.h: -------------------------------------------------------------------------------- 1 | /* 2 | A chess knight can move as indicated in the chess diagram below: 3 | 4 | https://assets.leetcode.com/uploads/2018/10/30/keypad.png 5 | 6 | This time, we place our chess knight on any numbered key of a phone pad (indicated above), and the knight makes N-1 hops. 7 | Each hop must be from one key to another numbered key. 8 | Each time it lands on a key (including the initial placement of the knight), it presses the number of that key, 9 | pressing N digits total. 10 | How many distinct numbers can you dial in this manner? 11 | Since the answer may be large, output the answer modulo 10^9 + 7. 12 | */ 13 | 14 | int knightDialer(int N) { 15 | vector> path={{4,6},{6,8},{7,9},{4,8},{0,3,9},{},{0,1,7},{2,6},{1,3},{2,4},{4,6}} ; 16 | vector prev(10,1); 17 | for(int n=2;n<=N;n++){ 18 | vector cur(10,0); 19 | for(int i=0;i<10;i++) 20 | for(auto j:path[i]) 21 | cur[i]=(cur[i]+prev[j])%1000000007; 22 | prev=cur; 23 | } 24 | int res=0; 25 | for(auto i:prev){ 26 | res=(res+i)%1000000007; 27 | } 28 | return res; 29 | } 30 | -------------------------------------------------------------------------------- /code/0962. Maximum Width Ramp.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j]. 3 | The width of such a ramp is j - i. 4 | 5 | Find the maximum width of a ramp in A. If one doesn't exist, return 0. 6 | 7 | Input: [6,0,8,2,1,5] 8 | Output: 4 9 | 10 | Input: [9,8,1,0,1,9,4,0,4,1] 11 | Output: 7 12 | */ 13 | 14 | int maxWidthRamp(vector& A) { 15 | stack s; 16 | int n=A.size(); 17 | for(int i=0;i A[i]) 19 | s.push(i); 20 | } 21 | int res=0; 22 | for(int i=n-1;!s.empty() && i>res;i--){ 23 | while(!s.empty() && A[s.top()]<=A[i]){ 24 | res=max(res,i-s.top()); 25 | s.pop(); 26 | } 27 | } 28 | return res; 29 | } 30 | -------------------------------------------------------------------------------- /code/0968. Binary Tree Cameras.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, we install cameras on the nodes of the tree. 3 | Each camera at a node can monitor its parent, itself, and its immediate children. 4 | Calculate the minimum number of cameras needed to monitor all nodes of the tree. 5 | 6 | Input: [0,0,null,0,0] 7 | Output: 1 8 | Explanation: One camera is enough to monitor all nodes if placed as shown. 9 | 10 | Input: [0,0,null,0,null,0,null,null,0] 11 | Output: 2 12 | Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement. 13 | */ 14 | 15 | class Solution { 16 | private: 17 | vector helper(TreeNode*root){ //{包含个数,child包含个数,parent包含个数} 18 | if(!root) return {1,0,0}; 19 | vector l=helper(root->left),r=helper(root->right); 20 | int i=1+min(l[0],min(l[1],l[2]))+min(r[0],min(r[1],r[2])); 21 | int j=min(l[0]+min(r[0],r[1]),r[0]+min(l[0],l[1])); 22 | int k=min(l[0],l[1])+min(r[0],r[1]); 23 | return {i,j,k}; 24 | } 25 | public: 26 | int minCameraCover(TreeNode* root) { 27 | vector res=helper(root); 28 | return min(res[0],res[1]); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /code/0969. Pancake Sorting.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A, we can perform a pancake flip: We choose some positive integer k <= A.length, 3 | then reverse the order of the first k elements of A. We want to perform zero or more pancake flips 4 | (doing them one after another in succession) to sort the array A. 5 | 6 | Return the k-values corresponding to a sequence of pancake flips that sort A. 7 | Any valid answer that sorts the array within 10 * A.length flips will be judged as correct. 8 | 9 | Input: [3,2,4,1] 10 | Output: [4,2,4,3] 11 | Explanation: 12 | We perform 4 pancake flips, with k values 4, 2, 4, and 3. 13 | Starting state: A = [3, 2, 4, 1] 14 | After 1st flip (k=4): A = [1, 4, 2, 3] 15 | After 2nd flip (k=2): A = [4, 1, 2, 3] 16 | After 3rd flip (k=4): A = [3, 2, 1, 4] 17 | After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted. 18 | 19 | Input: [1,2,3] 20 | Output: [] 21 | 22 | Note: 23 | 24 | 1 <= A.length <= 100 25 | A[i] is a permutation of [1, 2, ..., A.length] 26 | */ 27 | 28 | vector pancakeSort(vector& A) { 29 | int n=A.size(); 30 | vector res; 31 | for(int i=0;i& A, int K) { 9 | int n=A.size(),res=0; 10 | vector num(n+1,0); 11 | unordered_map m; 12 | m[0]=1; 13 | for(int i=0;ileft),r=helper(root->right); 21 | res=res+abs(l)+abs(r); //root 中多出来的只需要上移,已经计算过了 22 | return l+r+root->val-1; 23 | } 24 | public: 25 | int distributeCoins(TreeNode* root) { 26 | helper(root); 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /code/0986. Interval List Intersections.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order. 3 | Return the intersection of these two interval lists. 4 | 5 | (Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. 6 | The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. 7 | For example, the intersection of [1, 3] and [2, 4] is [2, 3].) 8 | 9 | Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]] 10 | Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] 11 | Reminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists. 12 | */ 13 | 14 | vector> intervalIntersection(vector>& A, vector>& B) { 15 | int n=A.size(),m=B.size(),i=0,j=0; 16 | vector> res; 17 | vector temp; 18 | while(i& A, int pos1,int pos2){ 16 | int n=sqrt(A[pos1]+A[pos2]); 17 | if(n*n==A[pos1]+A[pos2]) return true; 18 | else return false; 19 | } 20 | void backtrack(vector& A,int pos, int & res){ 21 | int n=A.size(); 22 | if(pos==n) res++; 23 | else{ 24 | unordered_map used; 25 | for(int i=pos;i& A) { 38 | int res=0; 39 | backtrack(A,0,res); 40 | return res; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /code/0997. Find the Town Judge.h: -------------------------------------------------------------------------------- 1 | /* 2 | In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. 3 | If the town judge exists, then: 4 | 5 | The town judge trusts nobody. 6 | Everybody (except for the town judge) trusts the town judge. 7 | There is exactly one person that satisfies properties 1 and 2. 8 | You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. 9 | 10 | If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1. 11 | 12 | Input: N = 3, trust = [[1,3],[2,3]] 13 | Output: 3 14 | 15 | Input: N = 3, trust = [[1,3],[2,3],[3,1]] 16 | Output: -1 17 | 18 | Input: N = 3, trust = [[1,2],[2,3]] 19 | Output: -1 20 | */ 21 | 22 | int findJudge(int N, vector>& trust) { 23 | vector count(N + 1, 0); 24 | for (auto t : trust) 25 | count[t[0]]--, count[t[1]]++; 26 | for (int i = 1; i <= N; ++i) 27 | if (count[i] == N - 1) 28 | return i; 29 | return -1; 30 | } 31 | -------------------------------------------------------------------------------- /code/1004. Max Consecutive Ones III.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A of 0s and 1s, we may change up to K values from 0 to 1. 3 | 4 | Return the length of the longest (contiguous) subarray that contains only 1s. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2 11 | Output: 6 12 | */ 13 | 14 | class Solution { 15 | public: 16 | int longestOnes(vector& A, int K) { 17 | //sliding windows 18 | int n=A.size(), res=0, cur=0, pos=0; 19 | for(int i=0;iK){ 23 | while(pos& A, int K) { 34 | //dp O(K*N) 超时 35 | vector res(K+1,0); 36 | int n=A.size(),ma=0; 37 | if(K>=n) return n; 38 | for(int i=0;i=1;j--) 45 | res[j]=res[j-1]+1; 46 | res[0]=0; 47 | } 48 | ma=max(ma,res[K]); 49 | } 50 | return ma; 51 | }*/ 52 | }; 53 | -------------------------------------------------------------------------------- /code/1008. Construct Binary Search Tree from Preorder Traversal: -------------------------------------------------------------------------------- 1 | /* 2 | Return the root node of a binary search tree that matches the given preorder traversal. 3 | (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, 4 | and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, 5 | then traverses node.left, then traverses node.right.) 6 | 7 | Input: [8,5,1,7,10,12] 8 | Output: [8,5,10,1,7,null,12] 9 | 10 | 1 <= preorder.length <= 100 11 | The values of preorder are distinct. 12 | */ 13 | 14 | class Solution { 15 | private: 16 | TreeNode* helper(vector& preorder, int &pos,int limit){ 17 | int n=preorder.size(); 18 | TreeNode *res=new TreeNode(preorder[pos]); 19 | if(pos+1left=helper(preorder, pos, preorder[pos-1]); 22 | } 23 | if(pos+1right=helper(preorder,pos,limit); 26 | } 27 | return res; 28 | } 29 | public: 30 | TreeNode* bstFromPreorder(vector& preorder) { 31 | int pos=0; 32 | return helper(preorder,pos,INT_MAX); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /code/1013. Partition Array Into Three Parts With Equal Sum.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums. 3 | 4 | Formally, we can partition the array if we can find indexes i+1 < j with 5 | (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1]) 6 | 7 | Input: [0,2,1,-6,6,-7,9,1,2,0,1] 8 | Output: true 9 | 10 | Input: [0,2,1,-6,6,7,9,-1,2,0,1] 11 | Output: false 12 | 13 | Input: [3,3,6,5,-2,2,5,1,-9,4] 14 | Output: true 15 | 16 | Note: 17 | 18 | 3 <= A.length <= 50000 19 | -10000 <= A[i] <= 10000 20 | */ 21 | 22 | bool canThreePartsEqualSum(vector& A) { 23 | int start=0,end=A.size()-1,sum=0,n=A.size(),res=0; 24 | for(auto i:A) sum+=i; 25 | if(sum%3) return false; 26 | sum/=3; 27 | while(startN/2;i--){ 12 | string n=bitset<32>(i).to_string(); //不能用std的to_string 13 | if(S.find(n.substr(n.find('1')))==string::npos) 14 | return false; 15 | } 16 | return true; 17 | } 18 | -------------------------------------------------------------------------------- /code/1017. Convert to Base -2.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two). 3 | The returned string must have no leading zeroes, unless the string is "0". 4 | 5 | Output: "110" 6 | Explantion: (-2) ^ 2 + (-2) ^ 1 = 2 7 | */ 8 | 9 | string baseNeg2(int N, string res = "") { 10 | while (N != 0) { 11 | int rem = N % -2; 12 | N /= -2; 13 | if (rem < 0) 14 | rem += 2, N += 1; 15 | res = to_string(rem) + res; 16 | } 17 | return max(string("0"), res); 18 | } 19 | -------------------------------------------------------------------------------- /code/1023. Camelcase Matching: -------------------------------------------------------------------------------- 1 | /* 2 | A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query. 3 | (We may insert each character at any position, and may insert 0 characters.) 4 | 5 | Given a list of queries, and a pattern, return an answer list of booleans, 6 | where answer[i] is true if and only if queries[i] matches the pattern. 7 | 8 | 9 | ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"] 10 | "FoBa" 11 | [true,false,true,false,false] 12 | */ 13 | 14 | class Solution { 15 | public: 16 | bool helper(const string & q, const string &p){ 17 | int n=q.size(),m=p.size(),i=0,j=0; 18 | while(i camelMatch(vector& queries, string pattern) { 34 | vector res; 35 | for(auto i: queries) 36 | res.push_back(helper(i,pattern)); 37 | return res; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /code/1024. Video Stitching.h: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a series of video clips from a sporting event that lasted T seconds. 3 | These video clips can be overlapping with each other and have varied lengths. 4 | 5 | Each video clip clips[i] is an interval: it starts at time clips[i][0] and ends at time clips[i][1]. 6 | We can cut these clips into segments freely: for example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7]. 7 | 8 | Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event ([0, T]). 9 | If the task is impossible, return -1. 10 | 11 | Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], T = 10 12 | Output: 3 13 | Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10]. 14 | */ 15 | 16 | int videoStitching(vector>& clips, int T) { 17 | sort(clips.begin(),clips.end()); 18 | int start=0,end=0,res=0; 19 | for(int i=0;iend) 21 | return -1; 22 | if(clips[i][0]>start){ 23 | start=end; 24 | res++; 25 | } 26 | end=max(end,clips[i][1]); 27 | if(end>=T) return res+1; 28 | } 29 | return -1; 30 | } 31 | -------------------------------------------------------------------------------- /code/1027. Longest Arithmetic Sequence.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A of integers, return the length of the longest arithmetic subsequence in A. 3 | Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, 4 | and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1). 5 | 6 | Input: [3,6,9,12] 7 | Output: 4 8 | 9 | Input: [9,4,7,2,10] 10 | Output: 3 11 | [4,7,10] 12 | 13 | Input: [20,1,15,3,10,5,8] 14 | Output: 4 15 | The longest arithmetic subsequence is [20,15,10,5]. 16 | */ 17 | 18 | int longestArithSeqLength(vector& A) { 19 | int n=A.size(); 20 | if(!n) return 0; 21 | int res=1; 22 | vector> dp(n); 23 | dp[0][0]=1; 24 | for(int i=1;i>& costs) { 12 | int n=costs.size(); 13 | nth_element(costs.begin(),costs.begin()+n/2,costs.end(),[](vector&a,vector&b){return a[0]-a[1]& A, vector& B) { 19 | int n=A.size(),m=B.size(); 20 | vector> dp(n+1,vector(m+1,0)); 21 | for(int i=0;i& A, int K) { 12 | int n=A.size(); 13 | vector dp(n,0); 14 | for(int i=0;i=0;j++){ 17 | ma=max(ma,A[i+1-j]); 18 | dp[i]=max(dp[i], ((i-j<0)?0:dp[i-j])+ma*j); 19 | } 20 | } 21 | return dp[n-1]; 22 | } 23 | -------------------------------------------------------------------------------- /code/1046. Last Stone Weight.h: -------------------------------------------------------------------------------- 1 | /* 2 | We have a collection of rocks, each rock has a positive integer weight. 3 | 4 | Each turn, we choose the two heaviest rocks and smash them together. Suppose the stones have weights x and y with x <= y. 5 | The result of this smash is: 6 | 7 | If x == y, both stones are totally destroyed; 8 | If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. 9 | At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) 10 | */ 11 | 12 | int lastStoneWeight(vector& stones) { 13 | priority_queue q; 14 | for(auto i:stones) q.push(i); 15 | while(q.size()>1){ 16 | int i=q.top(); 17 | q.pop(); 18 | int j=q.top(); 19 | q.pop(); 20 | if(i!=j) q.push(abs(i-j)); 21 | } 22 | return (q.size())?q.top():0; 23 | } 24 | -------------------------------------------------------------------------------- /code/1047. Remove All Adjacent Duplicates In String.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. 3 | We repeatedly make duplicate removals on S until we no longer can. 4 | Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. 5 | 6 | Input: "abbaca" 7 | Output: "ca" 8 | */ 9 | 10 | string removeDuplicates(string S) { 11 | string res=""; 12 | for(auto i:S){ 13 | if(res.size()&&res.back()==i) res.pop_back(); 14 | else res+=i; 15 | } 16 | return res; 17 | } 18 | -------------------------------------------------------------------------------- /code/1052. Grumpy Bookstore Owner.h: -------------------------------------------------------------------------------- 1 | /* 2 | Today, the bookstore owner has a store open for customers.length minutes. 3 | Every minute, some number of customers (customers[i]) enter the store, and all those customers leave after the end of that minute. 4 | 5 | On some minutes, the bookstore owner is grumpy. If the bookstore owner is grumpy on the i-th minute, grumpy[i] = 1, 6 | otherwise grumpy[i] = 0. When the bookstore owner is grumpy, the customers of that minute are not satisfied, 7 | otherwise they are satisfied. 8 | 9 | The bookstore owner knows a secret technique to keep themselves not grumpy for X minutes straight, but can only use it once. 10 | Return the maximum number of customers that can be satisfied throughout the day. 11 | 12 | Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3 13 | Output: 16 14 | */ 15 | 16 | int maxSatisfied(vector& customers, vector& grumpy, int X) { 17 | int n=grumpy.size(); 18 | int max_grumpy=0,sum_grumpy=0,sum_not_grumpy=0; 19 | for(int i=0;i=X && grumpy[i-X]) 25 | sum_grumpy-=customers[i-X]; 26 | max_grumpy=max(max_grumpy,sum_grumpy); 27 | } 28 | return sum_not_grumpy+max_grumpy; 29 | } 30 | -------------------------------------------------------------------------------- /code/1054. Distant Barcodes.h: -------------------------------------------------------------------------------- 1 | /* 2 | In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i]. 3 | Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists. 4 | 5 | Input: [1,1,1,2,2,2] 6 | Output: [2,1,2,1,2,1] 7 | Example 2: 8 | 9 | Input: [1,1,1,1,2,2,3,3] 10 | Output: [1,3,1,3,2,1,2,1] 11 | */ 12 | 13 | vector rearrangeBarcodes(vector& barcodes) { 14 | int n=barcodes.size(); 15 | unordered_map m; 16 | for(auto i:barcodes) m[i]++; 17 | set> s; 18 | for(auto i:m) s.insert({i.second,i.first}); 19 | vector res(n); 20 | int pos=0; 21 | for(auto ii=s.rbegin(); ii!=s.rend(); ++ii){ 22 | for(int i=0; i<(*ii).first; i++){ 23 | if(pos>=n) pos=1; 24 | res[pos]=(*ii).second; 25 | pos+=2; 26 | } 27 | } 28 | return res; 29 | } 30 | -------------------------------------------------------------------------------- /code/1055. Shortest Way to Form String.h: -------------------------------------------------------------------------------- 1 | /* 2 | From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions). 3 | Given two strings source and target, return the minimum number of subsequences of source 4 | such that their concatenation equals target. If the task is impossible, return -1. 5 | 6 | Input: source = "abc", target = "abcbc" 7 | Output: 2 8 | 9 | Input: source = "abc", target = "acdbc" 10 | Output: -1 11 | */ 12 | 13 | int shortestWay(string source, string target) { 14 | int n=source.size(),m=target.size(); 15 | vector visited(26,0); 16 | for(auto i: source) 17 | visited[i-'a']++; 18 | int pos=0; 19 | for(int i=0;i& nums, int K) { 19 | int start=nums[0], toFind=start+K; 20 | auto ii=upper_bound(nums.begin(),nums.end(),toFind); 21 | while(ii-nums.begin()-1>toFind-start-K){ 22 | toFind=start+K+(ii-nums.begin())-1; 23 | ii=upper_bound(nums.begin(),nums.end(),toFind); 24 | } 25 | return toFind; 26 | } 27 | -------------------------------------------------------------------------------- /code/1062. Longest Repeating Substring.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, find out the length of the longest repeating substring(s). Return 0 if no repeating substring exists. 3 | 4 | Input: "abcd" 5 | Output: 0 6 | 7 | Input: "abbaba" 8 | Output: 2 9 | 10 | Input: "aabcaabdaab" 11 | Output: 3 12 | Explanation: The longest repeating substring is "aab", which occurs 3 times. 13 | 14 | Input: "aaaaa" 15 | Output: 4 16 | 17 | The string S consists of only lowercase English letters from 'a' - 'z'. 18 | 1 <= S.length <= 1500 19 | */ 20 | 21 | //dp N^2 22 | int longestRepeatingSubstring(string S) { 23 | int n=S.size(),res=0; 24 | vector> dp(n+1,vector(n+1,0)); 25 | for(int i=1;i<=n;i++){ 26 | for(int j=i+1;j<=n;j++){ 27 | if(S[i-1]==S[j-1]){ 28 | dp[i][j]=dp[i-1][j-1]+1; 29 | res=max(res,dp[i][j]); 30 | } 31 | } 32 | } 33 | return res; 34 | } 35 | -------------------------------------------------------------------------------- /code/1063. Number of Valid Subarrays.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A of integers, return the number of non-empty continuous subarrays that satisfy the following condition: 3 | The leftmost element of the subarray is not larger than other elements in the subarray. 4 | 5 | Input: [1,4,2,5,3] 6 | Output: 11 7 | 8 | Input: [3,2,1] 9 | Output: 3 10 | 11 | Input: [2,2,2] 12 | Output: 6 13 | 14 | 1 <= A.length <= 50000 15 | 0 <= A[i] <= 100000 16 | */ 17 | 18 | int validSubarrays(vector& nums) { 19 | //Maintain monotonically increased values in a stack. 20 | //The size of the stack is the number of valid subarrays between the first and last element in the stack. 21 | vector s; 22 | int res=0; 23 | for (auto n : nums) { 24 | while (!s.empty() && n < s.back()) s.pop_back(); 25 | s.push_back(n); 26 | res += s.size(); 27 | } 28 | return res; 29 | } 30 | -------------------------------------------------------------------------------- /code/1065. Index Pairs of a String.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a text string and words (a list of strings), return all index pairs [i, j] so that the substring text[i]...text[j] 3 | is in the list of words. 4 | 5 | Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] 6 | Output: [[3,7],[9,13],[10,17]] 7 | 8 | Input: text = "ababa", words = ["aba","ab"] 9 | Output: [[0,1],[0,2],[2,3],[2,4]] 10 | 11 | Note: 12 | 13 | All strings contains only lowercase English letters. 14 | It's guaranteed that all strings in words are different. 15 | 1 <= text.length <= 100 16 | 1 <= words.length <= 20 17 | 1 <= words[i].length <= 50 18 | Return the pairs [i,j] in sorted order (i.e. sort them by their first coordinate in case of ties sort them 19 | by their second coordinate). 20 | */ 21 | 22 | vector> indexPairs(string text, vector& words) { 23 | vector> res; 24 | for(int i=0;istr2.size()) 19 | return gcdOfStrings(str2,str1); 20 | if(str1=="") return str2; 21 | if(str2.substr(0,str1.size())!=str1) return ""; 22 | return gcdOfStrings(str2.substr(str1.size()),str1); 23 | } 24 | -------------------------------------------------------------------------------- /code/1072. Flip Columns For Maximum Number of Equal Rows.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column. 3 | Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0. 4 | 5 | Return the maximum number of rows that have all values equal after some number of flips. 6 | 7 | Input: [[0,0,0],[0,0,1],[1,1,0]] 8 | Output: 2 9 | */ 10 | 11 | class Solution { 12 | private: 13 | void helper(unordered_map &m, vector &nums, int &res){ 14 | bool flip=nums[0]; 15 | string s; 16 | for(auto i:nums) 17 | s+=('0'+ ((flip)?1-i:i)); 18 | m[s]++; 19 | res=max(res,m[s]); 20 | } 21 | public: 22 | int maxEqualRowsAfterFlips(vector>& matrix) { 23 | unordered_map m; 24 | int res=0; 25 | for(int i=0; i< matrix.size();i++) 26 | helper(m, matrix[i], res); 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /code/1073. Adding Two Negabinary Numbers.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given two numbers arr1 and arr2 in base -2, return the result of adding them together. 4 | Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. 5 | For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. 6 | A number arr in array format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1. 7 | 8 | Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros. 9 | */ 10 | 11 | vector addNegabinary(vector& arr1, vector& arr2) { 12 | if(arr1.size()>arr2.size()) return addNegabinary(arr2,arr1); 13 | int n=arr1.size(),m=arr2.size(); 14 | for(int i=0;i>1); 22 | arr2[i]=(arr2[i]&1); 23 | } 24 | for(int i=m+1;i>=0;i--){ 25 | if(arr2[i]) break; 26 | else arr2.erase(arr2.begin()+i); 27 | } 28 | reverse(arr2.begin(),arr2.end()); 29 | return arr2.size()?arr2: vector{0}; 30 | } 31 | -------------------------------------------------------------------------------- /code/1074. Number of Submatrices That Sum to Target.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a matrix, and a target, return the number of non-empty submatrices that sum to target. 3 | 4 | A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2. 5 | 6 | Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: 7 | for example, if x1 != x1'. 8 | 9 | Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 10 | Output: 4 11 | 12 | Input: matrix = [[1,-1],[-1,1]], target = 0 13 | Output: 5 14 | */ 15 | 16 | int numSubmatrixSumTarget(vector>& matrix, int target) { 17 | int n=matrix.size(),m=matrix[0].size(); 18 | for(int i=0;i sum; 25 | sum[0]=1; 26 | int cur=0; 27 | for(int k=0; k> dp(n+1,vector(m+1,0)); 15 | for(int i=0;i0 || j>0;){ 26 | if(i>0 && dp[i][j]==dp[i-1][j]){ 27 | res+=str1[i-1]; 28 | i--; 29 | } 30 | else if(j>0 && dp[i][j]==dp[i][j-1]){ 31 | res+=str2[j-1]; 32 | j--; 33 | } 34 | else{ 35 | res+=str2[j-1]; 36 | i--;j--; 37 | } 38 | } 39 | 40 | reverse(res.begin(),res.end()); 41 | return res; 42 | } 43 | -------------------------------------------------------------------------------- /code/1100. Find K-Length Substrings With No Repeated Characters.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, return the number of substrings of length K with no repeated characters. 3 | 4 | Input: S = "havefunonleetcode", K = 5 5 | Output: 6 6 | 7 | Input: S = "home", K = 5 8 | Output: 0 9 | 10 | 1 <= S.length <= 10^4 11 | All characters of S are lowercase English letters. 12 | 1 <= K <= 10^4 13 | */ 14 | 15 | int numKLenSubstrNoRepeats(string S, int K) { 16 | int n=S.size(),start=0,res=0; 17 | vector count(26,0); 18 | for(int i=0;istart) 21 | count[S[start++]-'a']--; 22 | while(count[S[i]-'a']>1) 23 | count[S[start++]-'a']--; 24 | if(i-start==K-1) res++; 25 | } 26 | return res; 27 | } 28 | -------------------------------------------------------------------------------- /code/1109. Corporate Flight Bookings.h: -------------------------------------------------------------------------------- 1 | /* 2 | There are n flights, and they are labeled from 1 to n. 3 | We have a list of flight bookings. The i-th booking bookings[i] = [i, j, k] means that we booked k seats 4 | from flights labeled i to j inclusive. 5 | 6 | Return an array answer of length n, representing the number of seats booked on each flight in order of their label. 7 | 8 | Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5 9 | Output: [10,55,45,25,25] 10 | 11 | Constraints: 12 | 13 | 1 <= bookings.length <= 20000 14 | 1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000 15 | 1 <= bookings[i][2] <= 10000 16 | */ 17 | 18 | vector corpFlightBookings(vector>& bookings, int n) { 19 | //1 10 2 0 3 -10 4 0 5 0 20 | //1 10 2 20 3 -10 4 -20 5 0 21 | //1 10 2 45 3 -10 4 -20 5 0 22 | vector res(n,0); 23 | for(auto i: bookings){ 24 | res[i[0]-1]+=i[2]; 25 | if(i[1] helper(TreeNode* root){ 28 | if(!root) return {NULL,0}; 29 | auto l=helper(root->left),r=helper(root->right); 30 | if(l.second==r.second) 31 | return {root,l.second+1}; 32 | else if(l.second>r.second) 33 | return {l.first,l.second+1}; 34 | return{r.first, r.second+1}; 35 | } 36 | public: 37 | TreeNode* lcaDeepestLeaves(TreeNode* root) { 38 | return helper(root).first; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /code/1124. Longest Well-Performing Interval.h: -------------------------------------------------------------------------------- 1 | /* 2 | A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8. 3 | A well-performing interval is an interval of days for which the number of tiring days is strictly larger than 4 | the number of non-tiring days. 5 | 6 | Return the length of the longest well-performing interval. 7 | 8 | Input: hours = [9,9,6,0,6,6,9] 9 | Output: 3 10 | */ 11 | 12 | int longestWPI(vector& hours) { 13 | // <=8 减1,>8 加一; 14 | // sum连续的;如果有小于当前sum,长度是那个sum的后一个index到cur 15 | // -1 -1 -1 1 -1 -1 1 1 16 | //0 -1 -2 -3 -2 -3 -4 -3 -2 17 | unordered_map seen; 18 | int n=hours.size(),sum=0,res=0; 19 | for(int i=0;i8?1:-1); 21 | if(sum>0) res=i+1; //大于0,第一个前面是0 22 | else{ 23 | if(seen.count(sum-1)) //能找到小于sum的 24 | res=max(res,i-seen[sum-1]); 25 | if(!seen.count(sum)) //sum不在里面 26 | seen[sum]=i; 27 | } 28 | } 29 | return res; 30 | } 31 | -------------------------------------------------------------------------------- /code/1139. Largest 1-Bordered Square.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, 3 | or 0 if such a subgrid doesn't exist in the grid. 4 | 5 | Input: grid = [[1,1,1],[1,0,1],[1,1,1]] 6 | Output: 9 7 | Example 2: 8 | 9 | Input: grid = [[1,1,0,0]] 10 | Output: 1 11 | 12 | Constraints: 13 | 14 | 1 <= grid.length <= 100 15 | 1 <= grid[0].length <= 100 16 | grid[i][j] is 0 or 1 17 | */ 18 | 19 | int largest1BorderedSquare(vector>& grid) { 20 | int n=grid.size(),m=grid[0].size(); 21 | vector> row(n+1,vector(m+1,0)); 22 | vector> col=row; 23 | for(int i=0;i=1;i--) 30 | for(int j=i;j=i && col[j][k]>=i && row[j-i+1][k]>=i && col[j][k-i+1]>=i) 33 | return i*i; 34 | } 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /code/1155. Number of Dice Rolls With Target Sum.h: -------------------------------------------------------------------------------- 1 | /* 2 | You have d dice, and each die has f faces numbered 1, 2, ..., f. 3 | 4 | Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice 5 | so the sum of the face up numbers equals target. 6 | 7 | Input: d = 1, f = 6, target = 3 8 | Output: 1 9 | 10 | Input: d = 2, f = 6, target = 7 11 | Output: 6 12 | 13 | Input: d = 2, f = 5, target = 10 14 | Output: 1 15 | 16 | Input: d = 1, f = 2, target = 3 17 | Output: 0 18 | 19 | Input: d = 30, f = 30, target = 500 20 | Output: 222616187 21 | 22 | Constraints: 23 | 24 | 1 <= d, f <= 30 25 | 1 <= target <= 1000 26 | */ 27 | 28 | int numRollsToTarget(int d, int f, int target) { 29 | vector dp(target+1,0); 30 | dp[0]=1; 31 | for(int i=0;i temp(target+1,0); 34 | for(int k=1;k<=f;k++){ 35 | for(int j=0;j<=target-k-(d-i)+1 && j<=i*f;j++){ 36 | if(dp[j]) 37 | temp[j+k]=(dp[j]+temp[j+k])%(1000000007); 38 | } 39 | } 40 | dp=temp; 41 | } 42 | return dp[target]; 43 | } 44 | -------------------------------------------------------------------------------- /code/1190. Reverse Substrings Between Each Pair of Parentheses.h: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s that consists of lower case English letters and brackets. 3 | Reverse the strings in each pair of matching parentheses, starting from the innermost one. 4 | Your result should not contain any bracket. 5 | 6 | Input: s = "(abcd)" 7 | Output: "dcba" 8 | 9 | Input: s = "(u(love)i)" 10 | Output: "iloveu" 11 | 12 | Input: s = "(ed(et(oc))el)" 13 | Output: "leetcode" 14 | 15 | Input: s = "a(bcdefghijkl(mno)p)q" 16 | Output: "apmnolkjihgfedcbq" 17 | 18 | Constraints: 19 | 0 <= s.length <= 2000 20 | s only contains lower case English characters and parentheses. 21 | It's guaranteed that all parentheses are balanced. 22 | */ 23 | 24 | string reverseParentheses(string s) { 25 | int n=s.size(); 26 | vector stacks; 27 | stacks.push_back(""); 28 | for(int i=0;i& prob, int target) { 19 | vector res(target+1,0); 20 | res[0]=1.0; 21 | int n=prob.size(); 22 | if(n0;j--){ 25 | res[j]=res[j]*(1.0-prob[i-1])+res[j-1]*prob[i-1]; 26 | } 27 | res[0]*=(1.0-prob[i-1]); 28 | } 29 | return res[target]; 30 | } 31 | -------------------------------------------------------------------------------- /template/2D_DP1.cpp: -------------------------------------------------------------------------------- 1 | //需要考虑有一个没有(size多一个),这样初始化第一行/列,一定要先尝试这样用 2 | vector> dp(n+1,vector(m+1,0)); 3 | dp[0][0]= //单独初始化,如果之后初始化公式会越界 4 | for(int i=1;i res, vector data, vector path, int target, int cur){ //可能有length 13 | if(target==0 找到的条件){ //如果找到了,返回 14 | res.push_back(path); 15 | return; 16 | } 17 | for(int i=cur;i=(i+i+length-1)*length/2 19 | path.push_back(data[i]); 20 | helper(res,data,path,target-data[i],i); //可以重复i,不可重复i+1,有length限制,也-1 21 | path.pop_back(); //backtracking!! 22 | } 23 | return; 24 | } 25 | -------------------------------------------------------------------------------- /template/BackTracking2.cpp: -------------------------------------------------------------------------------- 1 | //find note in a tree, return the path to reach this node 2 | 3 | bool backtracking(TreeNode* root,vector &path,TreeNode* p){ //dfs+backtrack 找p 4 | if(root==p) return true; 5 | //tree 过left,right; vector for loop过后面所有可能(例如698) 6 | if(root->left) { 7 | path.push_back(root->left); 8 | if(backtracking(root->left, path, p)) return true; 9 | path.pop_back(); 10 | } 11 | if(root->right) { 12 | path.push_back(root->right); 13 | if(backtracking(root->right, path, p)) return true; 14 | path.pop_back(); 15 | } 16 | return false; 17 | } 18 | -------------------------------------------------------------------------------- /template/BinarySearch1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted (in ascending order) integer array nums of n elements and a target value, 3 | write a function to search target in nums. If target exists, then return its index, otherwise return -1. 4 | */ 5 | 6 | int left=0,right=n,mid; //r要保证大于target,所以是界外n,不是n-1 7 | while(lefttarget) right=mid; //先判断右侧,不能相等 11 | else left=mid+1; //l最后要换号,所以+1,以便和mid符号(target) right=mid-1; 22 | else left=mid+1; 23 | } 24 | return -1; 25 | -------------------------------------------------------------------------------- /template/BinarySearch2.cpp: -------------------------------------------------------------------------------- 1 | //Implement int sqrt(int x). 2 | 3 | int left=1, right=x,mid; 4 | while(left(). 找到的left>target; left-1<=target; return left-1 8 | //如果mid>=(). 找到的left>=target; left-1x/mid) 10 | right=mid; 11 | else 12 | left=mid+1; 13 | } 14 | return left-1; //因为一定能找到,所以while loop外返回,left-1是没发生相变最大的,left是相变发生后的 15 | -------------------------------------------------------------------------------- /template/DFS.cpp: -------------------------------------------------------------------------------- 1 | int dfs(vector>& grid,int i,int j,int n,int m){ 2 | if(grid[i][j]!=1) return 0; 3 | int res=1; 4 | grid[i][j]=2; 5 | vector pos={0,1,0,-1,0}; 6 | for(int k=0;k<4;k++){ 7 | int x=i+pos[k], y=j+pos[k+1]; 8 | if(x>=0 && x=0 && y dijkstra(vector>> &graph, int K){ //start from node K 2 | int n=graph.size(); 3 | vector res(n,INT_MAX); 4 | 5 | priority_queue,vector>, greater>> q; 6 | q.push({0,K-1}); 7 | 8 | while(!q.empty()){ 9 | pair cur=q.top(); 10 | q.pop(); 11 | if(res[cur.second]==INT_MAX){ 12 | res[cur.second]=cur.first; 13 | for(auto j:graph[cur.second]){ 14 | q.push({cur.first+j.second,j.first}); 15 | } 16 | } 17 | } 18 | return res; 19 | } 20 | -------------------------------------------------------------------------------- /template/SlidingWindow1.cpp: -------------------------------------------------------------------------------- 1 | int length_sub_k_different_nums(vector& tree) { //914 2 | unordered_map m; // key, count 3 | int start=0; 4 | int res=-1; 5 | for(int i=0;i root; 4 | public: 5 | //constructor 6 | Unionfind(int n){ 7 | root=vector(n+1,0); 8 | for(int i=0;i