├── .tmp ├── list ├── template.cpp └── template.py ├── README.md ├── c++ ├── 000_basic.cpp ├── 001_Two_Sum.cpp ├── 002_Add_Two_Numbers.cpp ├── 003_Longest_Substring_Without_Repeating_Characters.cpp ├── 004_Median_of_Two_Sorted_Arrays.cpp ├── 005_Longest_Palindromic_Substring.cpp ├── 006_ZigZag_Conversion.cpp ├── 007_Reverse_Integer.cpp ├── 008_String_to_Integer.cpp ├── 009_Palindrome_Number.cpp ├── 010_Regular_Expression_Matching.cpp ├── 011_Container_With_Most_Water.cpp ├── 012_Integer_to_Roman.cpp ├── 013_Roman_to_Integer.cpp ├── 014_Longest_Common_Prefix.cpp ├── 015_3Sum.cpp ├── 016_3Sum_Closest.cpp ├── 017_Letter_Combinations_of_a_Phone_Number.cpp ├── 018_4Sum.cpp ├── 019_Remove_Nth_Node_From_End_of_List.cpp ├── 020_Valid_Parentheses.cpp ├── 021_Merge_Two_Sorted_Lists.cpp ├── 022_Generate_Parentheses.cpp ├── 023_Merge_k_Sorted_Lists.cpp ├── 024_Swap_Nodes_in_Pairs.cpp ├── 025_Reverse_Nodes_in_k-Group.cpp ├── 026_Remove_Duplicates_from_Sorted_Array.cpp ├── 027_Remove_Element.cpp ├── 028_Implement.cpp ├── 029_Divide_Two_Integers.cpp ├── 030_Substring_with_Concatenation_of_All_Words.cpp ├── 031_Next_Permutation.cpp ├── 032_Longest_Valid_Parentheses.cpp ├── 033_Search_in_Rotated_Sorted_Array.cpp ├── 034_Search_for_a_Range.cpp ├── 035_Search_Insert_Position.cpp ├── 036_Valid_Sudoku.cpp ├── 037_Sudoku_Solver.cpp ├── 038_Count_and_Say.cpp ├── 039_Combination_Sum.cpp ├── 040_Combination_Sum_II.cpp ├── 041_First_Missing_Positive.cpp ├── 042_Trapping_Rain_Water.cpp ├── 043_Multiply_Strings.cpp ├── 044_Wildcard_Matching.cpp ├── 045_Jump_Game_II.cpp ├── 046_Permutations.cpp ├── 047_Permutations_II.cpp ├── 048_Rotate_Image.cpp ├── 049_Group_Anagrams.cpp ├── 050_Pow.cpp ├── 051_N-Queens.cpp ├── 053_Maximum_Subarray.cpp ├── 056_Merge_Intervals.cpp ├── 062_Unique_Paths.cpp ├── 063_Unique_Paths_II.cpp ├── 069_sqrt.cpp ├── 079_Word_Search.cpp ├── 088_Merge_Sorted_Array.cpp ├── 098_Validate_Binary_Search_Tree.cpp ├── 100_Same_Tree.cpp ├── 101_Symmetric_Tree.cpp ├── 102_Binary_Tree_Level_Order_Traversal.cpp ├── 103_Binary_Tree_Zigzag_Level_Order_Traversal.cpp ├── 104_Maximum_Depth_of_Binary_Tree.cpp ├── 105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.cpp ├── 106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.cpp ├── 107_Binary_Tree_Level_Order_Traversal_II.cpp ├── 108_Convert_Sorted_Array_to_Binary_Search_Tree.cpp ├── 109_Convert_Sorted_List_to_Binary_Search_Tree.cpp ├── 110_Balanced_Binary_Tree.cpp ├── 111_Minimum_Depth_of_Binary_Tree.cpp ├── 112_Path_Sum.cpp ├── 113_Path_Sum_II.cpp ├── 114_Flatten_Binary_Tree_to_Linked_List.cpp ├── 115_Distinct_Subsequences.cpp ├── 116_Populating_Next_Right_Pointers_in_Each_Node.cpp ├── 117_Populating_Next_Right_Pointers_in_Each_Node_II.cpp ├── 118_Pascal Triangle.cpp ├── 119_Pascals_Triangle_II.cpp ├── 120_Triangle.cpp ├── 121_Best_Time_to_Buy_and_Sell_Stock.cpp ├── 122_Best_Time_to_Buy_and_Sell_Stock_II.cpp ├── 123_Best_Time_to_Buy_and_Sell_Stock_III.cpp ├── 124_Binary_Tree_Maximum_Path_Sum.cpp ├── 125_Valid_Palindrome.cpp ├── 126_Word_Ladder_II.cpp ├── 127_Word_Ladder.cpp ├── 128_Longest_Consecutive_Sequence.cpp ├── 129_Sum_Root_to_Leaf_Numbers.cpp ├── 130_Surrounded_Regions.cpp ├── 131_Palindrome_Partitioning.cpp ├── 132_Palindrome_Partitioning_II.cpp ├── 133_Clone_Graph.cpp ├── 134_Gas_Station.cpp ├── 135_Candy.cpp ├── 136_Single_Number.cpp ├── 137_Single_Number_II.cpp ├── 138_Copy_List_with_Random_Pointer.cpp ├── 139_Word_Break.cpp ├── 140_Word_Break_II.cpp ├── 141_Linked_List_Cycle.cpp ├── 142_Linked_List_Cycle_II.cpp ├── 143_Reorder_List.cpp ├── 144_Binary_Tree_Preorder_Traversal.cpp ├── 145_Binary_Tree_Postorder_Traversal.cpp ├── 146_LRU_Cache.cpp ├── 147_Insertion_Sort_List.cpp ├── 148_Sort_List.cpp ├── 149_Max_Points_on_a_Line.cpp ├── 150_Evaluate_Reverse_Polish_Notation.cpp ├── 151_Reverse_Words_in_a_String.cpp ├── 152_Maximum_Product_Subarray.cpp ├── 153_Find_Minimum_in_Rotated_Sorted_Array.cpp ├── 154_Find_Minimum_in_Rotated_Sorted_Array_II.cpp ├── 155_Min_Stack.cpp ├── 157_Read_N_Characters_Given_Read4.cpp ├── 160_Intersection_of_Two_Linked_Lists.cpp ├── 162_Find_Peak_Element.cpp ├── 164_Maximum_Gap.cpp ├── 165_Compare_Version_Numbers.cpp ├── 166_Fraction_to_Recurring_Decimal.cpp ├── 167_Two_Sum_II_-_Input_array_is_sorted.cpp ├── 168_Excel_Sheet_Column_Title.cpp ├── 169_Majority_Element.cpp ├── 171_Excel_Sheet_Column_Number.cpp ├── 172_Factorial_Trailing_Zeroes.cpp ├── 173_Binary_Search_Tree_Iterator.cpp ├── 174_Dungeon_Game.cpp ├── 179_Largest_Number.cpp ├── 187_Repeated_DNA_Sequences.cpp ├── 188_Best_Time_to_Buy_and_Sell_Stock_IV.cpp ├── 189_Rotate_Array.cpp ├── 190_Reverse_Bits.cpp ├── 191_Number_of_1_Bits.cpp ├── 198_House_Robber.cpp ├── 199_Binary_Tree_Right_Side_View.cpp ├── 200_Number_of_Islands.cpp ├── 201_Bitwise_AND_of_Numbers_Range.cpp ├── 202_Happy_Number.cpp ├── 203_Remove_Linked_List_Elements.cpp ├── 204_Count_Primes.cpp ├── 205_Isomorphic_Strings.cpp ├── 206_Reverse_Linked_List.cpp ├── 207_Course_Schedule.cpp ├── 208_Implement_Trie.cpp ├── 209_Minimum_Size_Subarray_Sum.cpp ├── 210_Course_Schedule_II.cpp ├── 211_Add_and_Search_Word_-_Data_structure_design.cpp ├── 212_Word_Search_II.cpp ├── 213_House_Robber_II.cpp ├── 214_Shortest_Palindrome.cpp ├── 215_Kth_Largest_Element_in_an_Array.cpp ├── 216_Combination_Sum_III.cpp ├── 217_Contains_Duplicate.cpp ├── 218_The_Skyline_Problem.cpp ├── 219_Contains_Duplicate_II.cpp ├── 220_Contains_Duplicate_III.cpp ├── 221_Maximal_Square.cpp ├── 222_Count_Complete_Tree_Nodes.cpp ├── 223_Rectangle_Area.cpp ├── 224_Basic_Calculator.cpp ├── 225_Implement_Stack_using_Queues.cpp ├── 226_Invert_Binary_Tree.cpp ├── 227_Basic_Calculator_II.cpp ├── 228_Summary_Ranges.cpp ├── 229_Majority_Element_II.cpp ├── 230_Kth_Smallest_Element_in_a_BST.cpp ├── 231_Power_of_Two.cpp ├── 232_Implement_Queue_using_Stacks.cpp ├── 233_Number_of_Digit_One.cpp ├── 234_Palindrome_Linked_List.cpp ├── 235_Lowest_Common_Ancestor_of_a_Binary_Search_Tree.cpp ├── 236_Lowest_Common_Ancestor_of_a_Binary_Tree.cpp ├── 237_Delete_Node_in_a_Linked_List.cpp ├── 238_Product_of_Array_Except_Self.cpp ├── 239_Sliding_Window_Maximum.cpp ├── 240_Search_a_2D_Matrix_II.cpp ├── 241_Different_Ways_to_Add_Parentheses.cpp ├── 242_Valid_Anagram.cpp ├── 257_Binary_Tree_Paths.cpp ├── 258_Add_Digits.cpp ├── 260_Single_Number_III.cpp ├── 263_Ugly_Number.cpp ├── 264_Ugly_Number_II.cpp ├── 266_Palindrome_Permutation.cpp ├── 268_Missing_Number.cpp ├── 273_Integer_to_English_Words.cpp ├── 274_H-Index.cpp ├── 275_H-Index_II.cpp ├── 278_First_Bad_Version.cpp ├── 279_Perfect_Squares.cpp ├── 282_Expression_Add_Operators.cpp ├── 283_Move_Zeroes.cpp ├── 284_Peeking_Iterator.cpp ├── 287_Find_the_Duplicate_Number.cpp ├── 289_Game_of_Life.cpp ├── 290_Word_Pattern.cpp ├── 292_Nim_Game.cpp ├── 295_Find_Median_from_Data_Stream.cpp ├── 297_Serialize_and_Deserialize_Binary_Tree.cpp ├── 299_Bulls_and_Cows.cpp ├── 300_Longest_Increasing_Subsequence.cpp ├── 301_Remove_Invalid_Parentheses.cpp ├── 303_Range_Sum_Query_-_Immutable.cpp ├── 304_Range_Sum_Query_2D_-_Immutable.cpp ├── 306_Additive_Number.cpp ├── 307_Range_Sum_Query_-_Mutable.cpp ├── 309_Best_Time_to_Buy_and_Sell_Stock_with_Cooldown.cpp ├── 310_Minimum_Height_Trees.cpp ├── 312_Burst_Balloons.cpp ├── 313_Super_Ugly_Number.cpp ├── 315_Count_of_Smaller_Numbers_After_Self.cpp ├── 316_Remove_Duplicate_Letters.cpp ├── 318_Maximum_Product_of_Word_Lengths.cpp ├── 319_Bulb_Switcher.cpp ├── 322_Coin_Change.cpp ├── 324_Wiggle_Sort_II.cpp ├── 326_Power_of_Three.cpp ├── 328_Odd_Even_Linked_List.cpp ├── 329_Longest_Increasing_Path_in_a_Matrix.cpp ├── 331_Verify_Preorder_Serialization_of_a_Binary_Tree.cpp ├── 332_Reconstruct_Itinerary.cpp ├── 334_Increasing_Triplet_Subsequence.cpp ├── 335_Self_Crossing.cpp ├── 337_House_Robber_III.cpp ├── 338_Counting_Bits.cpp ├── 341_Flatten_Nested_List_Iterator.cpp ├── 342_Power_of_Four.cpp ├── 343_Integer_Break.cpp ├── 344_Reverse_String.cpp ├── 345_Reverse_Vowels_of_a_String.cpp ├── 347_Top_K_Frequent_Elements.cpp ├── 349_Intersection_of_Two_Arrays.cpp ├── 350_Intersection_of_Two_Arrays_II.cpp ├── 355_Design_Twitter.cpp ├── 357_Count_Numbers_with_Unique_Digits.cpp ├── 365_Water_and_Jug_Problem.cpp ├── 367_Valid_Perfect_Square.cpp ├── 368_Largest_Divisible_Subset.cpp ├── 371_Sum_of_Two_Integers.cpp ├── 372_Super_Pow.cpp ├── 373_Find_K_Pairs_with_Smallest_Sums.cpp ├── 374_Guess_Number_Higher_or_Lower.cpp ├── 375_Guess_Number_Higher_or_Lower_II.cpp ├── 376_Wiggle_Subsequence.cpp ├── 377_Combination_Sum_IV.cpp ├── 378_Kth_Smallest_Element_in_a_Sorted_Matrix.cpp ├── 380_Insert_Delete_GetRandom.cpp ├── 381_Insert_Delete_GetRandom_-_Duplicates_allowed.cpp ├── 382_Linked_List_Random_Node.cpp ├── 383_Ransom_Note.cpp ├── 384_Shuffle_an_Array.cpp ├── 385_Mini_Parser.cpp ├── 386_Lexicographical_Numbers.cpp ├── 387_First_Unique_Character_in_a_String.cpp ├── 388_Longest_Absolute_File_Path.cpp ├── 389_Find_the_Difference.cpp ├── 390_Elimination_Game.cpp ├── 392_Is_Subsequence.cpp ├── 393_UTF-8_Validation.cpp ├── 394_Decode_String.cpp ├── 395_Longest_Substring_with_At_Least_K_Repeating_Characters.cpp ├── 396_Rotate_Function.cpp ├── 397_Integer_Replacement.cpp ├── 398_Random_Pick_Index.cpp ├── 399_Evaluate_Division.cpp ├── 400_Nth_Digit.cpp ├── 401_Binary_Watch.cpp ├── 402_Remove_K_Digits.cpp ├── 404_Sum_of_Left_Leaves.cpp ├── 405_Convert_a_Number_to_Hexadecimal.cpp ├── 406_Queue_Reconstruction_by_Height.cpp ├── 409_Longest_Palindrome.cpp ├── 412_Fizz_Buzz.cpp ├── 413_Arithmetic_Slices.cpp ├── 414_Third_Maximum_Number.cpp ├── 415_Add_Strings.cpp ├── 416_Partition_Equal_Subset_Sum.cpp ├── 417_Pacific_Atlantic_Water_Flow.cpp ├── 419_Battleships_in_a_Board.cpp ├── 421_Maximum_XOR_of_Two_Numbers_in_an_Array.cpp ├── 433_Minimum_Genetic_Mutation.cpp ├── 434_Number_of_Segments_in_a_String.cpp ├── 435_Non-overlapping_Intervals.cpp ├── 437_Path_Sum_III.cpp ├── 438_Find_All_Anagrams_in_a_String.cpp ├── 441_Arranging_Coins.cpp ├── 442_FInd_All_Duplicates.cpp ├── 445_Add_Two_Numbers_2_Medium.cpp ├── 447_Number_of_Boomerangs.cpp ├── 448_Find_All_Numbers_Disappeared_in_an_Array.cpp ├── 451_Sort_Characters_By_Frequency.cpp ├── 453_Minimum_Moves_to_Equal_Array_Elements.cpp ├── 455_Assign_Cookies.cpp ├── 459_Repeated_Substring_Pattern.cpp ├── 461_Hamming_Distance.cpp ├── 462_Minimum_Moves_to_Equal_Array_Elements_II.cpp ├── 463_Island_Perimeter.cpp ├── 472_Concatenated_Words.cpp ├── 473_Matchsticks_to_Square.cpp ├── 475_Heaters.cpp ├── 476_Number_Complement.cpp ├── 485_Max_Consecutive_Ones.cpp ├── 491_Increasing_Subsequences.cpp ├── 492_Construct_the_Rectangle.cpp ├── 494_Target_Sum.cpp ├── 495_Teemo_Attacking.cpp ├── 496_Next_Generator_Element_1.cpp ├── 498_Diagonal_Traverse.cpp ├── 500_keyboard_row.cpp ├── 501_Find_Mode_In_Binary_Search_Tree.cpp ├── 503_Next_Greater_Element_2.cpp ├── 506_relative_ranks.cpp ├── 507_base_7.cpp ├── 508_Most_Frequent_SubTree_Sum.cpp ├── 513_find_bottom_left_tree.cpp ├── 515_find_largest_number_in_a_row.cpp ├── 520_Detect_Capital.cpp ├── 52_N-Queens_II.cpp ├── 530_Minimum_Absolute_Difference_in_BST.cpp ├── 54_Spiral_Matrix.cpp ├── 55_Jump_Game.cpp ├── 57_Insert_Interval.cpp ├── 58_Length_of_Last_Word.cpp ├── 59_Spiral_Matrix_II.cpp ├── 60_Permutation_Sequence.cpp ├── 61_Rotate_List.cpp ├── 64_Minimum_Path_Sum.cpp ├── 65_Valid_Number.cpp ├── 66_Plus_One.cpp ├── 67_Add_Binary.cpp ├── 68_Text_Justification.cpp ├── 70_Climbing_Stairs.cpp ├── 71_Simplify_Path.cpp ├── 72_Edit_Distance.cpp ├── 73_Set_Matrix_Zeroes.cpp ├── 74_Search_a_2D_Matrix.cpp ├── 75_Sort_Colors.cpp ├── 76_Minimum_Window_Substring.cpp ├── 77_Combinations.cpp ├── 78_Subsets.cpp ├── 80_Remove_Duplicates_from_Sorted_Array_II.cpp ├── 81_Search_in_Rotated_Sorted_Array_II.cpp ├── 82_Remove_Duplicates_from_Sorted_List_II.cpp ├── 83_Remove_Duplicates_from_Sorted_List.cpp ├── 84_Largest_Rectangle_in_Histogram.cpp ├── 85_Maximal_Rectangle.cpp ├── 86_Partition_List.cpp ├── 87_Scramble_String.cpp ├── 89_Gray_Code.cpp ├── 90_Subsets_II.cpp ├── 91_Decode_Ways.cpp ├── 92_Reverse_Linked_List_II.cpp ├── 93_Restore_IP_Addresses.cpp ├── 94_Binary_Tree_Inorder_Traversal.cpp ├── 95_Unique_Binary_Search_Trees_II.cpp ├── 96_Unique_Binary_Search_Trees.cpp ├── 97_Interleaving_String.cpp ├── 99_Recover_Binary_Search_Tree.cpp └── c++11.sublime.settting ├── framework.py ├── python ├── 01_Two_Sum.py ├── 02_Add_Two_Numbers.py ├── 03_Longest_Substring_Without_Repeating_Characters.py ├── 04_Median_of_Two_Sorted_Arrays.py ├── 05_Longest_Palindromic_Substring.py ├── 06_ZigZag_Conversion.py ├── 07_Reverse_Integer.py ├── 08_String_to_Integer.py ├── 09_Palindrome_Number.py ├── 100_Same_Tree.py ├── 10_Regular_Expression_Matching.py ├── 11_Container_With_Most_Water.py ├── 12_Integer_to_Roman.py ├── 13_Roman_to_Integer.py ├── 14_Longest_Common_Prefix.py ├── 15_3Sum.py ├── 16_3Sum_Closest.py ├── 17_Letter_Combinations_of_a_Phone_Number.py ├── 18_4Sum.py ├── 19_Remove_Nth_Node_From_End_of_List.py ├── 20_Valid_Parentheses.py ├── 21_Merge_Two_Sorted_Lists.py ├── 22_Generate_Parentheses.py ├── 23_Merge_k_Sorted_Lists.py ├── 24_Swap_Nodes_in_Pairs.py ├── 25_Reverse_Nodes_in_k-Group.py ├── 26_Remove_Duplicates_from_Sorted_Array.py ├── 27_Remove_Element.py ├── 28_Implement.py ├── 29_Divide_Two_Integers.py ├── 30_Substring_with_Concatenation_of_All_Words.py ├── 31_Next_Permutation.py ├── 32_Longest_Valid_Parentheses.py ├── 33_Search_in_Rotated_Sorted_Array.py ├── 34_Search_for_a_Range.py ├── 35_Search_Insert_Position.py ├── 36_Valid_Sudoku.py ├── 37_Sudoku_Solver.py ├── 38_Count_and_Say.py ├── 39_Combination_Sum.py ├── 40_Combination_Sum_II.py ├── 41_First_Missing_Positive.py ├── 42_Trapping_Rain_Water.py ├── 43_Multiply_Strings.py ├── 44_Wildcard_Matching.py ├── 45_Jump_Game_II.py ├── 46_Permutations.py ├── 47_Permutations_II.py ├── 48_Rotate_Image.py ├── 49_Group_Anagrams.py ├── 50_Pow.py ├── 51_N-Queens.py ├── 52_N-Queens_II.py ├── 53_Maximum_Subarray.py ├── 54_Spiral_Matrix.py ├── 55_Jump_Game.py ├── 56_Merge_Intervals.py ├── 57_Insert_Interval.py ├── 58_Length_of_Last_Word.py ├── 59_Spiral_Matrix_II.py ├── 60_Permutation_Sequence.py ├── 61_Rotate_List.py ├── 62_Unique_Paths.py ├── 63_Unique_Paths_II.py ├── 64_Minimum_Path_Sum.py ├── 65_Valid_Number.py ├── 66_Plus_One.py ├── 67_Add_Binary.py ├── 68_Text_Justification.py ├── 69_sqrt.py ├── 70_Climbing_Stairs.py ├── 71_Simplify_Path.py ├── 72_Edit_Distance.py ├── 73_Set_Matrix_Zeroes.py ├── 74_Search_a_2D_Matrix.py ├── 75_Sort_Colors.py ├── 76_Minimum_Window_Substring.py ├── 77_Combinations.py ├── 78_Subsets.py ├── 79_Word_Search.py ├── 80_Remove_Duplicates_from_Sorted_Array_II.py ├── 81_Search_in_Rotated_Sorted_Array_II.py ├── 82_Remove_Duplicates_from_Sorted_List_II.py ├── 83_Remove_Duplicates_from_Sorted_List.py ├── 84_Largest_Rectangle_in_Histogram.py ├── 85_Maximal_Rectangle.py ├── 86_Partition_List.py ├── 87_Scramble_String.py ├── 88_Merge_Sorted_Array.py ├── 89_Gray_Code.py ├── 90_Subsets_II.py ├── 91_Decode_Ways.py ├── 92_Reverse_Linked_List_II.py ├── 93_Restore_IP_Addresses.py ├── 94_Binary_Tree_Inorder_Traversal.py ├── 95_Unique_Binary_Search_Trees_II.py ├── 96_Unique_Binary_Search_Trees.py ├── 97_Interleaving_String.py ├── 98_Validate_Binary_Search_Tree.py └── 99_Recover_Binary_Search_Tree.py └── upload.sh /.tmp/template.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "000_basic.cpp" 16 | 17 | using namespace std; 18 | 19 | 20 | 21 | 22 | int main() { 23 | Solution s; 24 | Examples eg; 25 | } 26 | -------------------------------------------------------------------------------- /.tmp/template.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | 5 | 6 | 7 | 8 | 9 | class TestSolution(unittest.TestCase): 10 | def setUp(self): 11 | self.s = Solution() 12 | 13 | def test_method(self): 14 | """Such as self.assertEqual, self.assertTrue""" 15 | #self.assertEqual(self.s.) 16 | pass 17 | 18 | def main(): 19 | s = Solution() 20 | 21 | 22 | if __name__ == "__main__": 23 | unittest.main() 24 | -------------------------------------------------------------------------------- /c++/001_Two_Sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | /*Given nums = [2, 7, 11, 15], target = 9, 15 | 16 | Because nums[0] + nums[1] = 2 + 7 = 9, 17 | return [0, 1]. 18 | 19 | take care of [4, 4], target = 8 20 | */ 21 | 22 | class Solution { 23 | public: 24 | vector twoSum(vector& nums, int target) { 25 | unordered_map mp; 26 | vector vec; 27 | for (int i = 0; i < nums.size(); i++) { 28 | int left = target - nums[i]; 29 | if (mp.find(left) != mp.end()) { 30 | vec.push_back(i); 31 | vec.push_back(mp[left]); 32 | return vec; 33 | } 34 | mp[nums[i]] = i; 35 | } 36 | return vec; 37 | } 38 | }; 39 | 40 | 41 | int main() { 42 | Solution s; 43 | Examples eg; 44 | } 45 | -------------------------------------------------------------------------------- /c++/002_Add_Two_Numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "000_basic.cpp" 11 | 12 | using namespace std; 13 | 14 | class Solution { 15 | public: 16 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 17 | ListNode *head = new ListNode(0); 18 | ListNode *l = head; 19 | int sum, carry = 0; 20 | while (l1 || l2 || carry) { 21 | sum = carry; 22 | carry = 0; 23 | if (l1) { // this way makes the code more simple 24 | sum += l1->val; 25 | l1 = l1->next; 26 | } 27 | if (l2) { 28 | sum += l2->val; 29 | l2 = l2->next; 30 | } 31 | if (sum > 9) { 32 | sum -= 10; 33 | carry = 1; 34 | } 35 | l->next = new ListNode(sum); 36 | l = l->next; 37 | } 38 | return head->next; 39 | } 40 | }; 41 | 42 | -------------------------------------------------------------------------------- /c++/003_Longest_Substring_Without_Repeating_Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | int last = -1; 5 | int maximum = 0; 6 | int n = s.size(); 7 | unordered_map dict; 8 | for (int i = 0; i < n; i++) { 9 | if ((dict.count(s[i]) != 0) && (last < dict[s[i]])) last = dict[s[i]]; 10 | dict[s[i]] = i; 11 | maximum = max(i - last, maximum); // the original one or the next one between two points 12 | } 13 | return maximum; 14 | } 15 | }; -------------------------------------------------------------------------------- /c++/006_ZigZag_Conversion.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | string convert(string s, int nRows) { 5 | if ((s.size() <= nRows) or (nRows < 2)) 6 | return s; 7 | string sub; 8 | for (int i = 0; i < nRows; i++) { 9 | int tmp = 0; 10 | while (tmp + i < s.size()) { 11 | if ((i > 0) and (i < nRows - 1) and (tmp > i)) 12 | sub.push_back(s[tmp - i]); 13 | sub.push_back(s[tmp + i]); 14 | tmp += 2 * (nRows - 1); 15 | } 16 | if ((tmp + i >= s.size()) and (tmp - i < s.size()) and (i < nRows - 1)) 17 | sub.push_back(s[tmp - i]); 18 | } 19 | return sub; 20 | } 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /c++/007_Reverse_Integer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | class Solution { 15 | public: 16 | int reverse(int x) { 17 | int out = 0; 18 | while (x){ 19 | // Take care of overflow 20 | if (out > INT_MAX/10 || out < INT_MIN/10){ 21 | return 0; 22 | } 23 | out = out * 10 + x % 10; 24 | x = x / 10; 25 | } 26 | return out; 27 | } 28 | }; 29 | 30 | 31 | 32 | int main() { 33 | Solution s; 34 | cout << s.reverse(1534236469) << endl; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /c++/011_Container_With_Most_Water.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int maxArea(vector& height) { 12 | int water, out = 0; 13 | int left = 0; 14 | int right = height.size() - 1; 15 | while (left < right) { 16 | water = min(height[left], height[right]) * (right - left); 17 | // cout << water << " " << left << " " << right << endl; 18 | if (out < water) out = water; 19 | if (height[left] < height[right]) left += 1; 20 | else right -= 1; 21 | } 22 | return out; 23 | } 24 | 25 | 26 | }; 27 | 28 | int main() { 29 | Solution s; 30 | vector height; 31 | height.push_back(1); 32 | height.push_back(2); 33 | height.push_back(0); 34 | height.push_back(3); 35 | 36 | cout << s.maxArea(height) << endl; 37 | } 38 | -------------------------------------------------------------------------------- /c++/012_Integer_to_Roman.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | string intToRoman(int num) { 13 | int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 14 | string numerals[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 15 | string out; 16 | for (int i = 0; i < 13; i++) { 17 | while (num >= values[i]) { 18 | num -= values[i]; 19 | //out.append(numerals[i]); 20 | out += numerals[i]; 21 | } 22 | } 23 | return out; 24 | } 25 | }; 26 | 27 | 28 | int main() { 29 | Solution s; 30 | cout << s.intToRoman(50) << endl; 31 | } 32 | -------------------------------------------------------------------------------- /c++/014_Longest_Common_Prefix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | string longestCommonPrefix(vector& strs) { 12 | string lcp = ""; 13 | if (strs.size() < 1) 14 | return lcp; 15 | for (int i = 0; i < strs[0].size(); i++) { 16 | for (int j = 1; j < strs.size(); j++) { 17 | if (i > strs[j].size() || strs[0][i] != strs[j][i]) 18 | return lcp; 19 | } 20 | lcp.push_back(strs[0][i]); 21 | } 22 | return lcp; 23 | } 24 | }; 25 | 26 | 27 | int main() { 28 | Solution s; 29 | vector strs; 30 | strs.push_back("abc"); 31 | strs.push_back("abd"); 32 | cout << s.longestCommonPrefix(strs) << endl; 33 | } 34 | -------------------------------------------------------------------------------- /c++/017_Letter_Combinations_of_a_Phone_Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class Solution { 11 | public: 12 | vector letterCombinations(string digits) { 13 | vector res; 14 | if (digits == "") 15 | return res; 16 | res.push_back(""); 17 | 18 | string Lists[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 19 | 20 | for (int i = 0; i < digits.size(); i++) { 21 | vector tmp; 22 | for (int j = 0; j < res.size(); j++){ 23 | string tmpStr = Lists[digits[i] - '0']; 24 | for (int k = 0; k < tmpStr.size(); k++) { 25 | tmp.push_back(res[j] + tmpStr[k]); 26 | } 27 | } 28 | res = tmp; 29 | } 30 | return res; 31 | } 32 | }; 33 | 34 | 35 | int main() { 36 | Solution s; 37 | vector str; 38 | str = s.letterCombinations("23"); 39 | for (int i = 0; i < str.size(); i++) 40 | cout << str[i] << endl; 41 | 42 | } 43 | -------------------------------------------------------------------------------- /c++/020_Valid_Parentheses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | bool isValid(string s) { 13 | stack stk; 14 | for (int i = 0; i < s.size(); i++) { 15 | if (s[i] == '(' || s[i] == '[' || s[i] == '{') 16 | stk.push(s[i]); 17 | else { 18 | if (stk.empty() || unmatch(stk.top(), s[i])) 19 | return false; 20 | stk.pop(); 21 | } 22 | } 23 | return stk.empty(); 24 | } 25 | bool unmatch(char a, char b) { 26 | if (a == '(') 27 | return (b != ')'); 28 | else if (a == '[') 29 | return (b != ']'); 30 | else if (a == '{') 31 | return (b != '}'); 32 | else 33 | return false; 34 | } 35 | }; 36 | 37 | 38 | int main() { 39 | Solution s; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /c++/021_Merge_Two_Sorted_Lists.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * struct ListNode { 13 | * int val; 14 | * ListNode *next; 15 | * ListNode(int x) : val(x), next(NULL) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 21 | ListNode *head = new ListNode(0); 22 | ListNode *tmp = head; 23 | while (l1 && l2) { 24 | if (l1->val < l2->val) { 25 | tmp->next = l1; 26 | l1 = l1->next; 27 | } 28 | else{ 29 | tmp->next = l2; 30 | l2 = l2->next; 31 | } 32 | tmp = tmp->next; 33 | } 34 | // useful commands 35 | tmp->next = l1 ? l2 : l1; 36 | return head->next; 37 | } 38 | }; 39 | 40 | 41 | int main() { 42 | Solution s; 43 | 44 | } 45 | -------------------------------------------------------------------------------- /c++/022_Generate_Parentheses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class Solution { 11 | public: 12 | vector generateParenthesis(int n) { 13 | vector allCombo; 14 | string combo; 15 | backTracking(n, 0, 0, combo, allCombo); 16 | return allCombo; 17 | 18 | } 19 | // passing by reference, be sure to change allCombo 20 | void backTracking(int n, int left, int right, string combo, vector &allCombo) { 21 | 22 | if (left == n && right == n) 23 | allCombo.push_back(combo); 24 | if (left < n) 25 | backTracking(n, left + 1, right, combo + '(', allCombo); 26 | if (right < left) 27 | backTracking(n, left, right + 1, combo + ')', allCombo); 28 | } 29 | }; 30 | 31 | int main() { 32 | Solution s; 33 | vector res; 34 | res = s.generateParenthesis(3); 35 | for (int i = 0; i < res.size(); i++) 36 | cout << res[i] << " "; 37 | cout << endl; 38 | 39 | } 40 | -------------------------------------------------------------------------------- /c++/023_Merge_k_Sorted_Lists.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * struct ListNode { 12 | * int val; 13 | * ListNode *next; 14 | * ListNode(int x) : val(x), next(NULL) {} 15 | * }; 16 | */ 17 | 18 | class Solution { 19 | public: 20 | ListNode* mergeKLists(vector& lists) { 21 | if (lists.size() == 0) 22 | return NULL; 23 | int left, right = lists.size() - 1; 24 | while (right > 0) { 25 | left = 0; 26 | while (left < right) 27 | lists[left] = two_merge(lists[left++], lists[right--]); 28 | } 29 | return lists[0]; 30 | } 31 | 32 | ListNode* two_merge(ListNode *a, ListNode *b) { 33 | ListNode *head = new ListNode(0); 34 | ListNode *out = head; 35 | while (a && b) { 36 | if (a->val < b->val) { 37 | out->next = a; 38 | a = a->next; 39 | } 40 | else { 41 | out ->next = b; 42 | b = b->next; 43 | } 44 | out = out->next; 45 | } 46 | out->next = a ? a : b; 47 | return head->next; 48 | } 49 | }; 50 | 51 | int main() { 52 | Solution s; 53 | vector ss; 54 | } 55 | -------------------------------------------------------------------------------- /c++/026_Remove_Duplicates_from_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class Solution { 11 | public: 12 | int removeDuplicates(vector& nums) { 13 | int n = nums.size(); 14 | if (n <= 1) 15 | return n; 16 | int i = 0; 17 | int j = 1; 18 | while (i < n - j) { 19 | if (nums[i] == nums[i + 1]) { 20 | nums.erase(nums.begin() + i); 21 | j++; 22 | } 23 | else 24 | i++; 25 | } 26 | return nums.size(); 27 | } 28 | }; 29 | 30 | 31 | class Solution { 32 | public: 33 | int removeDuplicates(vector& nums) { 34 | int n = nums.size(); 35 | if (n < 2) return n; 36 | int idx = 1; 37 | for (int i = 1; i < n; i++) { 38 | if (nums[i] != nums[i-1]) 39 | nums[idx++] = nums[i]; 40 | } 41 | return idx; 42 | } 43 | }; 44 | 45 | int main() { 46 | Solution s; 47 | int dat[] = {1, 2, 2, 3, 3, 4}; 48 | vector set(dat, dat + 6); 49 | cout << set.size() << endl; 50 | cout << s.removeDuplicates(set) << endl; 51 | 52 | } 53 | -------------------------------------------------------------------------------- /c++/027_Remove_Element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int removeElement(vector& nums, int val) { 12 | int n = nums.size(); 13 | int i = 0; 14 | int j = 0; 15 | while (i < n - j) { 16 | if (nums[i] == val) { 17 | nums.erase(nums.begin() + i); 18 | j++; 19 | } 20 | else 21 | i++; 22 | } 23 | return nums.size(); 24 | } 25 | }; 26 | 27 | 28 | 29 | int main() { 30 | Solution s; 31 | int dat[] = {1, 2, 2, 3, 3, 4}; 32 | vector set(dat, dat + 6); 33 | cout << set.size() << endl; 34 | cout << s.removeElement(set, 3) << endl; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /c++/028_Implement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class Solution{ 11 | public: 12 | int strStr(string haystack, string needle) { 13 | int m = needle.size(); 14 | int n = haystack.size(); 15 | if (m == 0) 16 | return 0; 17 | if (n == 0) 18 | return -1; 19 | 20 | for (int i = 0; i < n - m + 1; i++) { 21 | int j = 0; 22 | while (j < m) { 23 | char p = haystack[i + j]; 24 | char q = needle[j]; 25 | if (p == q) 26 | j++; 27 | else 28 | break; 29 | } 30 | if (j == m) 31 | return i; 32 | } 33 | return -1; 34 | } 35 | }; 36 | 37 | 38 | int main() { 39 | Solution s; 40 | cout << s.strStr("abcde", "bc") << endl; 41 | 42 | } 43 | -------------------------------------------------------------------------------- /c++/029_Divide_Two_Integers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | /* 11 | * Take care of overflow 12 | * use bit shift operator, since we are not allowed to use that 13 | * Y / x = a <=> Y = a * x <=> Y = a * (2^i + 2^j + ...) 14 | */ 15 | 16 | 17 | class Solution { 18 | public: 19 | int divide(int dividend, int divisor) { 20 | unsigned int divd = dividend, divs = divisor; 21 | if (divisor < 0) 22 | divs = -divs; 23 | if (dividend < 0) 24 | divd = -divd; 25 | if (dividend == INT_MIN && divisor == -1) 26 | return INT_MAX; 27 | int sign = 1; 28 | if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) 29 | sign = -1; 30 | 31 | int res = 0; 32 | while(divd >= divs) 33 | { 34 | long long a = divs; // in case of overflow 35 | int i; 36 | for(i = 0; a <= divd; i++) 37 | a <<= 1; 38 | res += (1 << (i-1)); 39 | divd -= (divs << (i-1)); 40 | } 41 | 42 | return sign * res; 43 | } 44 | }; 45 | 46 | 47 | int main() { 48 | Solution s; 49 | cout << s.divide(16, 3) << endl; 50 | cout << s.divide(1, 2) << endl; 51 | } 52 | -------------------------------------------------------------------------------- /c++/031_Next_Permutation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // Math trick, understand what does permuatation mean. 10 | // Permutation explanation: 11 | // https://www.nayuki.io/page/next-lexicographical-permutation-algorithm 12 | 13 | 14 | class Solution { 15 | public: 16 | void nextPermutation(vector& nums) { 17 | int n = nums.size(); 18 | if (n < 2) 19 | return; 20 | // i = 0 is wrong, since we want to the first that disobey the rule from the right 21 | int i = n - 2; 22 | while(i >= 0 && nums[i] >= nums[i + 1]) 23 | i--; 24 | if (i < 0) { 25 | sort(nums.begin(), nums.end()); 26 | return; 27 | } 28 | int j = i + 1; 29 | while (j <= n - 1 && nums[j] > nums[i]) // num[j] >= num[i] wrong 30 | j++; 31 | j--; 32 | cout << "i = " << i << " j = " << j << " " << nums[i] << nums[i + 1] << endl; 33 | swap(nums[i], nums[j]); 34 | sort(nums.begin() + i + 1, nums.end()); 35 | } 36 | }; 37 | 38 | 39 | int main() { 40 | Solution s; 41 | //int vec[] = {0, 1, 2, 5, 3, 3, 0}; 42 | int vec[] = {1, 5, 1}; 43 | 44 | //cout << sizeof(vec) / sizeof(int) << endl; 45 | vector v(vec, vec + sizeof(vec) / sizeof(int)); 46 | 47 | s.nextPermutation(v); 48 | 49 | for (int i = 0; i < v.size(); i++) 50 | cout << v[i] << endl; 51 | } 52 | -------------------------------------------------------------------------------- /c++/035_Search_Insert_Position.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | class Solution { 10 | public: 11 | int searchInsert(vector& nums, int target) { 12 | int loc = binSearch(nums, target, 0, nums.size() - 1); 13 | if (nums[loc] == target) 14 | return loc; 15 | else if (nums[loc] < target) 16 | return loc + 1; 17 | return 0; 18 | } 19 | 20 | int binSearch(vector &nums, int target, int left, int right) { 21 | int loc, n = right - left + 1; 22 | if (n == 1) 23 | return left; 24 | int mid = left + n / 2; 25 | if (nums[mid] <= target) 26 | loc = binSearch(nums, target, mid, right); 27 | else 28 | loc = binSearch(nums, target, left, mid - 1); 29 | return loc; 30 | } 31 | }; 32 | 33 | int main() { 34 | 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /c++/036_Valid_Sudoku.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | class Solution { 10 | public: 11 | bool isValidSudoku(vector > & board) { 12 | if (board.size() != 9 or board[0].size() != 9) return false; 13 | unordered_map > row, col, grid; 14 | for (int i = 0; i < 9; i++) { 15 | for (int j = 0; j < 9; j++) { 16 | if (board[i][j] == '.') continue; 17 | int num = i / 3 * 3 + j / 3; 18 | if (row[i].count(board[i][j]) > 0 || col[j].count(board[i][j]) > 0 || grid[num].count(board[i][j]) > 0) return false; 19 | row[i][board[i][j]] = 0; 20 | col[j][board[i][j]] = 0; 21 | grid[num][board[i][j]] = 0; 22 | } 23 | } 24 | return true; 25 | } 26 | }; 27 | 28 | int main() { 29 | Solution s; 30 | vector > board; 31 | string str[] = {"7...4....","...865...",".1.2.....",".....9...","....5.5..",".........","......2..",".........","........."}; 32 | 33 | // useful way to assign values to 2D vector 34 | for (int i = 0; i < 9; i++) { 35 | vector tmp; 36 | for (int j = 0; j < 9; j++) 37 | tmp.push_back(str[i][j]); 38 | board.push_back(tmp); 39 | } 40 | cout << s.isValidSudoku(board) << endl; 41 | } 42 | -------------------------------------------------------------------------------- /c++/038_Count_and_Say.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | string countAndSay(int n) { 11 | string s = "1"; 12 | for (int i = 2; i < n + 1; i++) 13 | s = count(s); 14 | return s; 15 | } 16 | 17 | string count(string s) { 18 | 19 | int count = 0; 20 | int n = s.size(); 21 | 22 | char last = '.'; 23 | string res = ""; 24 | 25 | for (int i = 0; i < n; i++) { 26 | if (last != '.' && last != s[i]) { 27 | res += to_string(count) + last; 28 | count = 0; 29 | } 30 | count++; 31 | last = s[i]; 32 | } 33 | 34 | res += to_string(count) + last; 35 | 36 | return res; 37 | } 38 | }; 39 | 40 | int main() { 41 | 42 | Solution s; 43 | cout << s.countAndSay(1) << endl; 44 | 45 | } 46 | -------------------------------------------------------------------------------- /c++/041_First_Missing_Positive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | class Solution { 10 | public: 11 | int firstMissingPositive(vector& A) { 12 | int i = 0; 13 | int n = A.size(); 14 | while (i < n) 15 | { 16 | cout << i << " new step "; 17 | for (int j = 0; j < n; j++) 18 | cout << A[j] << " "; 19 | cout << endl; 20 | if (A[i] != (i+1) && A[i] >= 1 && A[i] <= n && A[A[i]-1] != A[i]) { 21 | // if A[i] is not in the right direction, swap it to the right direction 22 | swap(A[i], A[A[i]-1]); 23 | } 24 | else 25 | i++; 26 | } 27 | for (i = 0; i < n; ++i) 28 | if (A[i] != (i+1)) 29 | return i+1; 30 | return n+1; 31 | } 32 | }; 33 | 34 | 35 | int main() { 36 | Solution s; 37 | int A[] = {3, 2, 5, 0, 7, -1,6, 1, 4}; 38 | vector B(A, A + sizeof(A) / sizeof(int)); 39 | cout << s.firstMissingPositive(B) << endl; 40 | } 41 | -------------------------------------------------------------------------------- /c++/043_Multiply_Strings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class Solution { 11 | public: 12 | string multiply(string num1, string num2) { 13 | reverse(num1.begin(), num1.end()); 14 | reverse(num2.begin(), num2.end()); 15 | int m = num1.size(), n = num2.size(); 16 | int digit, carry, arr[m + n] = {0}; 17 | for (int i = 0; i < m; i++) 18 | for (int j = 0; j < n; j++) 19 | arr[i + j] += (num1[i] - '0') * (num2[j] - '0'); 20 | 21 | string ans = ""; 22 | for (int i = 0; i < m + n; i++) { 23 | digit = arr[i] % 10; 24 | carry = arr[i] / 10; 25 | if (i != m + n - 1) 26 | arr[i + 1] += carry; 27 | ans = to_string(digit) + ans; 28 | } 29 | 30 | while (ans[0] == '0' && ans.size() > 1) 31 | ans.erase(ans.begin()); 32 | return ans; 33 | } 34 | }; 35 | 36 | 37 | int main() { 38 | Solution s; 39 | string num1, num2; 40 | num1 = "123", num2= "987"; 41 | cout << s.multiply(num1, num2) << endl; 42 | 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /c++/044_Wildcard_Matching.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | class Solution { 10 | public: 11 | bool isMatch(string s, string p) { 12 | int i = 0, j = 0, sloc = 0, star = -1; 13 | while (i < s.size()) { 14 | if (j < p.size() && (s[i] == p[j] || p[j] == '?')) { 15 | i++; j++; 16 | } 17 | else if (j < p.size() && (p[j] == '*')) { 18 | star = j; 19 | j++; 20 | sloc = i;// 21 | } 22 | else if (star != -1) { 23 | j = star + 1; 24 | sloc++; 25 | i = sloc; 26 | } 27 | else 28 | return false; 29 | } 30 | while (j < p.size() and p[j] == '*') 31 | j++; 32 | if (j == p.size()) 33 | return true; 34 | return false; 35 | } 36 | }; 37 | 38 | 39 | int main() { 40 | Solution s; 41 | cout << s.isMatch("acacac", "ac*ac") << endl; 42 | cout << s.isMatch("aa", "a") << endl; 43 | cout << s.isMatch("ho", "ho**") << endl; 44 | 45 | } 46 | -------------------------------------------------------------------------------- /c++/045_Jump_Game_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class Solution { 11 | public: 12 | int jump(vector& nums) { 13 | int n = nums.size(); 14 | int jumpM = 0, lastJump = 0; 15 | int i = 0, k = 0, tag = 0; 16 | while (jumpM < n - 1) { 17 | while (i <= lastJump) { 18 | jumpM = max(jumpM, i + nums[i]); 19 | if (jumpM < i + 1) { 20 | tag = 1; 21 | break; 22 | } 23 | i++; 24 | } 25 | k++; 26 | lastJump = jumpM; 27 | } 28 | if (tag) 29 | return 0; 30 | return k; 31 | } 32 | }; 33 | 34 | 35 | int main() { 36 | Solution s; 37 | } -------------------------------------------------------------------------------- /c++/046_Permutations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | class Solution { 10 | public: 11 | vector > permute(vector& nums) { 12 | int n = nums.size(); 13 | vector > res; 14 | if (n <= 1) { 15 | res.push_back(nums); 16 | return res; 17 | } 18 | for (int i = 0; i < n; i++) { 19 | vector > tmp; 20 | vector copy = nums; 21 | copy.erase(copy.begin() + i); 22 | 23 | tmp = permute(copy); 24 | for (int j = 0; j < tmp.size(); j++) { 25 | tmp[j].push_back(nums[i]); 26 | res.push_back(tmp[j]); 27 | } 28 | } 29 | return res; 30 | } 31 | }; 32 | 33 | 34 | int main() { 35 | Solution s; 36 | int dats[] = {0, 1, 2}; 37 | vector dat(dats, dats + sizeof(dats) / sizeof(int)); 38 | vector > res = s.permute(dat); 39 | 40 | cout << "-----------------------" << endl; 41 | for (int i = 0; i < res.size(); i++) { 42 | cout << "-----------------------" << i << " ......" << endl; 43 | for (int j = 0; j < res[i].size(); j++) { 44 | cout << res[i][j] << " "; 45 | } 46 | cout << endl; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /c++/047_Permutations_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | 11 | class Solution { 12 | public: 13 | vector > permuteUnique(vector& nums) { 14 | int n = nums.size(); 15 | sort(nums.begin(), nums.end()); 16 | vector > res; 17 | if (n <= 1) { 18 | res.push_back(nums); 19 | return res; 20 | } 21 | int last = nums[0] - 1; // make sure they are not the same 22 | for (int i = 0; i < n; i++) { 23 | if (last == nums[i]) // recursion only when new element appears 24 | continue; 25 | vector tmp = nums; 26 | tmp.erase(tmp.begin() + i); 27 | vector > res_part = permuteUnique(tmp); 28 | for (int j = 0; j < res_part.size(); j++) { 29 | res_part[j].push_back(nums[i]); 30 | res.push_back(res_part[j]); 31 | } 32 | last = nums[i]; 33 | } 34 | return res; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /c++/048_Rotate_Image.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | 10 | class Solution { 11 | public: 12 | void rotate(vector>& matrix) { 13 | for (int i = 0; i < matrix.size(); i++) { 14 | for (int j = i + 1; j < matrix[i].size(); j++) { 15 | int tmp = matrix[i][j]; 16 | matrix[i][j] = matrix[j][i]; 17 | matrix[j][i] = tmp; 18 | } 19 | } 20 | for (int i = 0; i < matrix.size(); i++) 21 | reverse(matrix[i].begin(), matrix[i].end()); 22 | return matrix; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /c++/050_Pow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class Solution2 { 11 | public: 12 | double myPow(double x, int n) { 13 | if (n == 0) 14 | return 1; 15 | if (n < 0) { 16 | if (n == -pow(2, 31)) 17 | return x * myPow(x, n + 1); 18 | return 1 / myPow(x, -n); 19 | } 20 | if (n == 1) 21 | return x; 22 | double y = myPow(x, n / 2); 23 | y *= y; 24 | if (n % 2 == 1) 25 | y *= x; 26 | return y; 27 | } 28 | }; 29 | 30 | class Solution { 31 | public: 32 | double myPow(double x, int n) { 33 | if (n < 0) { 34 | if (n == -pow(2, 31)) return 1 / myPow(x, INT_MAX) / x; 35 | return 1 / myPow(x, -n); 36 | } 37 | if (n == 0) return 1; 38 | if (n == 1) return x; 39 | int i = 1; 40 | double out = x; 41 | while ((unsigned long long)(i * 2) < n) { 42 | out *= out; 43 | i *= 2; 44 | } 45 | cout << out << endl; 46 | return out * myPow(x, n - i); 47 | } 48 | }; 49 | 50 | int main() { 51 | Solution s; 52 | // cout << s.myPow(-1, -2147483648) << endl; 53 | cout << (pow(2, 31) % 10) << endl; 54 | // cout << s.myPow(2, 2147483647) << endl; 55 | } 56 | -------------------------------------------------------------------------------- /c++/053_Maximum_Subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int maxSubArray(vector& nums) { 12 | // dp[i]: maximum value from left to i 13 | int n = nums.size(); 14 | if (n == 0) return -1; 15 | int dp[n] = {0}; 16 | dp[0] = nums[0]; 17 | int maxN = dp[0]; 18 | for (int i = 1; i < n; i++) { 19 | dp[i] = max(dp[i-1] + nums[i], nums[i]); 20 | maxN = max(maxN, dp[i]); 21 | } 22 | return maxN; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /c++/062_Unique_Paths.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int uniquePaths(int m, int n) { 12 | if (m == 1 || n == 1) 13 | return 1; 14 | int dp[m + 1][n + 1] = {{0}}; 15 | for (int i = 0; i < m + 1; i++) 16 | dp[i][1] = 1; 17 | for (int i = 1; i < n + 1; i++) 18 | dp[1][i] = 1; 19 | for (int i = 1; i < m; i++) { 20 | for (int j = 1; j < n; j++) { 21 | dp[i + 1][j + 1] = dp[i][j + 1] + dp[i + 1][j]; 22 | } 23 | } 24 | return dp[m][n]; 25 | } 26 | }; 27 | 28 | 29 | int main() { 30 | Solution s; 31 | cout << s.uniquePaths(10, 10) << endl; 32 | } -------------------------------------------------------------------------------- /c++/063_Unique_Paths_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class Solution { 11 | public: 12 | int uniquePathsWithObstacles(vector >& obstacleGrid) { 13 | int m = obstacleGrid.size(); 14 | int n = obstacleGrid[0].size(); 15 | int dp[m][n] = {{0}}; 16 | dp[0][0] = 1 - obstacleGrid[0][0]; 17 | for (int i = 1; i < m; i++) 18 | dp[i][0] = dp[i - 1][0] * (1 - obstacleGrid[i][0]); 19 | for (int i = 1; i < n; i++) 20 | dp[0][i] = dp[0][i - 1] * (1 - obstacleGrid[0][i]); 21 | for (int i = 0; i < m - 1; i++) { 22 | for (int j = 0; j < n - 1; j++) { 23 | dp[i + 1][j + 1] = dp[i + 1][j] * (1 - obstacleGrid[i + 1][j]) + dp[i][j + 1] * (1 - obstacleGrid[i][j + 1]); 24 | } 25 | } 26 | return dp[m - 1][n - 1] * (1 - obstacleGrid[m - 1][n - 1]); 27 | } 28 | }; 29 | 30 | int main() { 31 | int dat[] = {0, 0}; 32 | vector > vec; 33 | vector tmp(dat, dat + 2); 34 | vec.push_back(tmp); 35 | Solution s; 36 | cout << s.uniquePathsWithObstacles(vec) << endl; 37 | 38 | } -------------------------------------------------------------------------------- /c++/088_Merge_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // failed in microsoft interview, what a pity 9 | class Solution { 10 | public: 11 | void merge(vector& nums1, int m, vector& nums2, int n) { 12 | int i = m - 1, j = n - 1, k = n + m - 1; 13 | while (i >= 0 && j >= 0) nums1[k--] = nums1[i] > nums2[j]? nums1[i--]:nums2[j--]; 14 | while (j >= 0) nums1[k--] = nums2[j--]; 15 | 16 | } 17 | }; 18 | 19 | 20 | class Solution { // simplified version 21 | public: 22 | void merge(vector& nums1, int m, vector& nums2, int n) { 23 | int i = m - 1, j = n - 1, tar = m + n - 1; 24 | while (j >= 0) nums1[tar--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; 25 | } 26 | }; 27 | 28 | int main() { 29 | Solution s; 30 | vector nums1; 31 | vector nums2; 32 | nums1.push_back(1); 33 | s.merge(nums1, 1, nums2, 0); 34 | } 35 | -------------------------------------------------------------------------------- /c++/102_Binary_Tree_Level_Order_Traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "func.cpp" 10 | 11 | using namespace std; 12 | 13 | /* 14 | [3,9,20,null,null,15,7], 15 | 3 16 | / \ 17 | 9 20 18 | / \ 19 | 15 7 20 | 21 | [ 22 | [3], 23 | [9,20], 24 | [15,7] 25 | ]*/ 26 | 27 | class Solution { 28 | public: 29 | vector > levelOrder(TreeNode* root) { 30 | vector > res; 31 | queue Q; 32 | if (!root) return res; 33 | Q.push(root); 34 | while (!Q.empty()) { 35 | vector level; 36 | int size = Q.size(); 37 | for (int i = 0; i < size; i++) { // make sure to be in the same level 38 | TreeNode* subtree = Q.front(); 39 | Q.pop(); 40 | level.push_back(subtree->val); 41 | if (subtree->left) Q.push(subtree->left); 42 | if (subtree->right) Q.push(subtree->right); 43 | } 44 | res.push_back(level); 45 | } 46 | return res; 47 | } 48 | }; 49 | 50 | int main() { 51 | Solution s; 52 | Examples eg; 53 | 54 | vector > res = s.levelOrder(eg.setTree0()); 55 | print2dVector(res); 56 | } 57 | -------------------------------------------------------------------------------- /c++/104_Maximum_Depth_of_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | 13 | 14 | class Solution { 15 | public: 16 | int maxDepth(TreeNode* root) { 17 | if (!root) return 0; 18 | return max(maxDepth(root->left), maxDepth(root->right)) + 1; 19 | } 20 | }; 21 | 22 | int main() { 23 | Solution s; 24 | } 25 | -------------------------------------------------------------------------------- /c++/107_Binary_Tree_Level_Order_Traversal_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "func.cpp" 10 | 11 | using namespace std; 12 | 13 | 14 | class Solution { 15 | public: 16 | vector > levelOrderBottom(TreeNode* root) { 17 | vector > res; 18 | if (!root) return res; 19 | queue q; 20 | q.push(root); 21 | 22 | while (!q.empty()) { 23 | vector level; 24 | int size = q.size(); 25 | for (int i = 0; i < size; i++) { // make sure to be in the same level 26 | TreeNode* sub = q.front(); 27 | q.pop(); 28 | level.push_back(sub->val); 29 | if (sub->left) q.push(sub->left); 30 | if (sub->right) q.push(sub->right); 31 | } 32 | res.push_back(level); 33 | } 34 | reverse(res.begin(), res.end()); 35 | return res; 36 | } 37 | }; 38 | 39 | int main() { 40 | Solution s; 41 | Examples eg; 42 | vector > res = s.levelOrderBottom(eg.setTree0()); 43 | print2dVector(res); 44 | 45 | } 46 | -------------------------------------------------------------------------------- /c++/110_Balanced_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | class Solution { 15 | public: 16 | bool isBalanced(TreeNode* root) { 17 | return dfs(root); 18 | } 19 | bool dfs(TreeNode* root) { 20 | if (!root) return true; 21 | int l = maxDepth(root->left); 22 | int r = maxDepth(root->right); 23 | if ( abs(l - r) > 1) return false; 24 | else return dfs(root->left) && dfs(root->right); 25 | } 26 | 27 | int maxDepth(TreeNode * root) { 28 | if (!root) return 0; 29 | return max(maxDepth(root->left), maxDepth(root->right)) + 1; 30 | } 31 | }; 32 | 33 | 34 | int main() { 35 | Solution s; 36 | Examples eg; 37 | cout << s.isBalanced(eg.setTree0()) << endl; 38 | } 39 | -------------------------------------------------------------------------------- /c++/111_Minimum_Depth_of_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | class Solution { 15 | public: 16 | int minDepth(TreeNode* root) { 17 | if (!root) return 0; 18 | else if (!root->left && !root->right) return 1; 19 | else if (!root->left && root->right) return minDepth(root->right) + 1; 20 | else if (root->left && !root->right) return minDepth(root->left) + 1; 21 | else return min(minDepth(root->left), minDepth(root->right)) + 1; 22 | } 23 | }; 24 | 25 | 26 | int main() { 27 | Solution s; 28 | Examples eg; 29 | } 30 | -------------------------------------------------------------------------------- /c++/112_Path_Sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | 15 | class Solution { 16 | public: 17 | bool hasPathSum(TreeNode* root, int sum) { 18 | if (!root) return false; 19 | return dfs(root, sum); 20 | } 21 | bool dfs(TreeNode* root, int sum) { 22 | if (!root) { 23 | if (sum == 0) 24 | return true; 25 | else 26 | return false; 27 | } 28 | int v = sum - root->val; 29 | if (!root->left && root->right) return dfs(root->right, v); 30 | else if (root->left && !root->right) return dfs(root->left, v); 31 | else return dfs(root->left, v) or dfs(root->right, v); 32 | } 33 | }; 34 | 35 | 36 | 37 | int main() { 38 | Solution s; 39 | Examples eg; 40 | TreeNode* t0 = new TreeNode(1); 41 | TreeNode* t1 = new TreeNode(2); 42 | t0->left = t1; 43 | cout << s.hasPathSum(t0, 1) << endl; 44 | 45 | } 46 | -------------------------------------------------------------------------------- /c++/113_Path_Sum_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | class Solution { 15 | public: 16 | vector > pathSum(TreeNode* root, int sum) { 17 | vector > res; 18 | if (!root) return res; 19 | vector tmp; 20 | dfs(root, sum, tmp, res); 21 | return res; 22 | } 23 | void dfs(TreeNode* root, int sum, vector tmp, vector > & res) { 24 | if (!root) { 25 | if (sum == 0) res.push_back(tmp); 26 | return; 27 | } 28 | int v = root->val; 29 | tmp.push_back(v); 30 | if (root->left) dfs(root->left, sum - v, tmp, res); // if-condition helps delete repetition 31 | if (root->right) dfs(root->right, sum - v, tmp, res); // ... 32 | if (!root->left && !root->right) { // take care the node without child 33 | if (sum == v) res.push_back(tmp); 34 | return; 35 | } 36 | } 37 | }; 38 | 39 | 40 | int main() { 41 | Solution s; 42 | Examples eg; 43 | } 44 | -------------------------------------------------------------------------------- /c++/117_Populating_Next_Right_Pointers_in_Each_Node_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | /** 15 | * Definition for binary tree with next pointer. 16 | * struct TreeLinkNode { 17 | * int val; 18 | * TreeLinkNode *left, *right, *next; 19 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 20 | * }; 21 | */ 22 | 23 | 24 | class Solution { 25 | public: 26 | void connect(TreeLinkNode *root) { 27 | if (!root) return; 28 | queue q; 29 | q.push(root); 30 | while(!q.empty()) { 31 | int n = q.size(); 32 | for (int i = 0; i < n; i++) { 33 | TreeLinkNode *cur = q.front(); q.pop(); 34 | if (i != n - 1) cur->next = q.front(); 35 | else cur->next = NULL; 36 | if (cur->left) q.push(cur->left); 37 | if (cur->right) q.push(cur->right); 38 | } 39 | } 40 | } 41 | }; 42 | 43 | 44 | int main() { 45 | Solution s; 46 | Examples eg; 47 | } 48 | -------------------------------------------------------------------------------- /c++/118_Pascal Triangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | 15 | class Solution { 16 | public: 17 | vector > generate(int numRows) { 18 | vector > res; 19 | if (numRows == 0) return res; 20 | vector row; 21 | row.push_back(1); 22 | if (numRows == 1) { 23 | res.push_back(row); 24 | return res; 25 | } 26 | else if (numRows == 2) { 27 | res.push_back(row); 28 | row.push_back(1); 29 | res.push_back(row); 30 | return res; 31 | } 32 | vector > last = generate(numRows - 1); 33 | for (int i = 0; i < numRows - 2; i++) { 34 | row.push_back(last[numRows - 2][i] + last[numRows - 2][i + 1]); 35 | } 36 | row.push_back(1); 37 | last.push_back(row); 38 | return last; 39 | } 40 | }; 41 | 42 | int main() { 43 | Solution s; 44 | Examples eg; 45 | vector > res = s.generate(4); 46 | print2dVector(res); 47 | 48 | 49 | } -------------------------------------------------------------------------------- /c++/121_Best_Time_to_Buy_and_Sell_Stock.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | /* 13 | Example 1: 14 | Input: [7, 1, 5, 3, 6, 4] 15 | Output: 5 16 | 17 | max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 18 | Example 2: 19 | Input: [7, 6, 4, 3, 1] 20 | Output: 0 21 | 22 | In this case, no transaction is done, i.e. max profit = 0.*/ 23 | 24 | /* 25 | Trick here, only to record the minimum value, return the maximum profit 26 | 27 | */ 28 | 29 | class Solution { 30 | public: 31 | int maxProfit(vector& prices) { 32 | int minPrice = INT_MAX, profit = 0; 33 | for (int i = 0; i < prices.size(); i++) { 34 | if (minPrice > prices[i]) 35 | minPrice = prices[i]; 36 | profit = max(profit, prices[i] - minPrice); 37 | } 38 | return profit; 39 | } 40 | }; 41 | 42 | 43 | int main() { 44 | Solution s; 45 | } 46 | -------------------------------------------------------------------------------- /c++/122_Best_Time_to_Buy_and_Sell_Stock_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | /* 13 | 122. Best Time to Buy and Sell Stock II 14 | Say you have an array for which the ith element is the price of a given stock on day i. 15 | 16 | Design an algorithm to find the maximum profit. You may complete as many transactions 17 | as you like (ie, buy one and sell one share of the stock multiple times). However, you 18 | may not engage in multiple transactions at the same time (ie, you must sell the stock 19 | before you buy again). 20 | */ 21 | 22 | // as long as profit comes, add to total profit. 23 | 24 | class Solution { 25 | public: 26 | int maxProfit(vector& prices) { 27 | int profit = 0; 28 | for (int i = 1; i < prices.size(); i++) { 29 | if (prices[i] > prices[i-1]) 30 | profit += prices[i] - prices[i-1]; 31 | } 32 | return profit; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /c++/124_Binary_Tree_Maximum_Path_Sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | 17 | class Solution { 18 | int postOrder(TreeNode* root, int &maxSum) { 19 | if (!root) return 0; 20 | int l = max(0, postOrder(root->left, maxSum)); 21 | int r = max(0, postOrder(root->right, maxSum)); 22 | maxSum = max(maxSum, l + r + root->val); 23 | return root->val + max(l, r); 24 | } 25 | public: 26 | int maxPathSum(TreeNode* root) { 27 | int maxSum = INT_MIN; 28 | postOrder(root, maxSum); 29 | return maxSum; 30 | } 31 | }; 32 | 33 | int main() { 34 | Solution s; 35 | Examples eg; 36 | } 37 | -------------------------------------------------------------------------------- /c++/125_Valid_Palindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | class Solution { 15 | public: 16 | bool isPalindrome(string s) { 17 | int left = 0, right = s.size() - 1; 18 | while (left < right) { 19 | while (left < s.size() - 1 && !isalnum(s[left])) left++; 20 | while (right > 0 && !isalnum(s[right])) right--; 21 | //cout << left << " " << right << endl; 22 | if (left >= right) return true; 23 | if (tolower(s[left++]) != tolower(s[right--])) return false; // take care of left++, right++ 24 | } 25 | return true; 26 | } 27 | }; 28 | 29 | int main() { 30 | Solution s; 31 | Examples eg; 32 | cout << s.isPalindrome("......a.....") << endl; 33 | } 34 | -------------------------------------------------------------------------------- /c++/128_Longest_Consecutive_Sequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | class Solution { 18 | public: 19 | int longestConsecutive(vector& nums) { 20 | unordered_set st(nums.begin(), nums.end()); 21 | int cnt = 1; 22 | for (int i : nums) { 23 | if (st.count(i) == 0) continue; 24 | st.erase(i); 25 | int prev = i - 1, next = i + 1; 26 | while (st.count(prev) > 0) st.erase(prev--); // without erase still works, yet too slow, avoid repeating 27 | while (st.count(next) > 0) st.erase(next++); 28 | cnt = max(cnt, next - prev - 1); 29 | } 30 | return cnt; 31 | } 32 | }; 33 | 34 | 35 | int main() { 36 | Solution s; 37 | Examples eg; 38 | } 39 | -------------------------------------------------------------------------------- /c++/129_Sum_Root_to_Leaf_Numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | // DFS 17 | 18 | class Solution { 19 | public: 20 | int sumNumbers(TreeNode* root) { 21 | if (!root) return 0; 22 | int res = 0; 23 | DFS(root, res, ""); 24 | return res; 25 | } 26 | 27 | void DFS(TreeNode* root, int& res, string s) { 28 | if (root) { 29 | if (root->left) DFS(root->left, res, s + to_string(root->val)); 30 | if (root->right) DFS(root->right, res, s + to_string(root->val)); 31 | if (!root->left && !root->right) { 32 | s += to_string(root->val); 33 | res += stoi(s); 34 | } 35 | } 36 | else res += stoi(s); 37 | } 38 | }; 39 | 40 | int main() { 41 | Solution s; 42 | Examples eg; 43 | TreeNode *t0 = new TreeNode(1); 44 | TreeNode *t1 = new TreeNode(2); 45 | TreeNode *t2 = new TreeNode(3); 46 | TreeNode *t3 = new TreeNode(1); 47 | 48 | t0->left = t1; 49 | t0->right = t2; 50 | //t1->right = t3; 51 | cout << s.sumNumbers(t0) << endl; 52 | } 53 | -------------------------------------------------------------------------------- /c++/134_Gas_Station.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | // if A could go to B, while A can't go to C, this means B can't go to C 18 | class Solution { 19 | public: 20 | int canCompleteCircuit(vector& gas, vector& cost) { 21 | int start = 0, total = 0, tank = 0; 22 | for (int i = 0; i < gas.size(); i++) { 23 | tank += gas[i] - cost[i]; 24 | if (tank < 0) { 25 | start = i + 1; 26 | total += tank; // if total is not negative in the end, there must be a solution 27 | tank = 0; 28 | } 29 | } 30 | return total + tank < 0? -1: start; // why + tank? [1,2], [2,1], in the last, we didn't + tank 31 | } 32 | }; 33 | 34 | 35 | int main() { 36 | Solution s; 37 | Examples eg; 38 | } 39 | -------------------------------------------------------------------------------- /c++/141_Linked_List_Cycle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | class Solution { 15 | public: // great idea, create two pointers 16 | //the fast one will approach the slow one one step once 17 | bool hasCycle(ListNode *head) { 18 | while (!head) return false; 19 | ListNode *fast = head, *slow = head; 20 | while (slow->next && fast->next) { 21 | slow = slow->next; 22 | fast = fast->next; 23 | if (fast->next) { 24 | fast = fast->next; 25 | if (fast == slow) return true; 26 | } 27 | else break; 28 | } 29 | return false; 30 | } 31 | }; 32 | 33 | 34 | int main() { 35 | Solution s; 36 | Examples eg; 37 | ListNode *n = new ListNode(1); 38 | n->next = n; 39 | cout << s.hasCycle(n) << endl; 40 | } 41 | -------------------------------------------------------------------------------- /c++/144_Binary_Tree_Preorder_Traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | 18 | class Solution { 19 | public: 20 | vector preorderTraversal(TreeNode* root) { 21 | vector res; 22 | dfs(root, res); 23 | return res; 24 | } 25 | 26 | void dfs(TreeNode* root, vector &res) { 27 | if (root) { 28 | res.push_back(root->val); 29 | if (root->left) dfs(root->left, res); 30 | if (root->right) dfs(root->right, res); 31 | } 32 | } 33 | }; 34 | 35 | int main() { 36 | Solution s; 37 | Examples eg; 38 | } 39 | -------------------------------------------------------------------------------- /c++/145_Binary_Tree_Postorder_Traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | // instead of using recursion, we use iteration 18 | 19 | class Solution { 20 | public: 21 | vector postorderTraversal(TreeNode* root) { 22 | vector res; 23 | if (!root) return res; 24 | 25 | stack stk; 26 | stk.push(root); 27 | 28 | while(!stk.empty()) { 29 | TreeNode* node = stk.top(); stk.pop(); 30 | res.insert(res.begin(), node->val); 31 | if (node->left) stk.push(node->left); 32 | if (node->right) stk.push(node->right); 33 | } 34 | return res; 35 | } 36 | }; 37 | 38 | 39 | int main() { 40 | Solution s; 41 | Examples eg; 42 | } 43 | -------------------------------------------------------------------------------- /c++/162_Find_Peak_Element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | class Solution { 18 | public: 19 | int findPeakElement(vector& nums) { 20 | int left = 0, right = nums.size() - 1; 21 | while (left < right) { 22 | int mid = left + (right - left) / 2; 23 | if (nums[mid] < nums[mid + 1]) left = mid + 1; 24 | else right = mid; 25 | } 26 | return left; 27 | } 28 | }; 29 | 30 | 31 | int main() { 32 | Solution s; 33 | Examples eg; 34 | } 35 | -------------------------------------------------------------------------------- /c++/165_Compare_Version_Numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | 17 | /* 18 | 1.1 1.10 19 | 20 | 0.1 0.0.1 1 21 | 22 | 01 1 0 23 | */ 24 | 25 | 26 | class Solution { 27 | public: 28 | int compareVersion(string version1, string version2) { 29 | for (auto &w : version1) w = (w == '.')? ' ' : w; 30 | for (auto &w : version2) w = (w == '.')? ' ' : w; 31 | istringstream s1(version1), s2(version2); 32 | while (1) { 33 | int n1, n2; 34 | if (not (s1 >> n1)) n1 = 0; // determine if s1 >> n1 has gone to the end point 35 | if (not (s2 >> n2)) n2 = 0; 36 | if (not s1 and not s2) return 0; // not n1, n2 37 | if (n1 < n2) return -1; 38 | if (n1 > n2) return 1; 39 | } 40 | } 41 | }; 42 | 43 | int main() { 44 | Solution s; 45 | Examples eg; 46 | cout << s.compareVersion("0.1", "0.0.1") << endl; 47 | } 48 | -------------------------------------------------------------------------------- /c++/167_Two_Sum_II_-_Input_array_is_sorted.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | 18 | /* 19 | Input: numbers={2, 7, 11, 15}, target=9 20 | Output: index1=1, index2=2*/ 21 | 22 | class Solution { 23 | public: 24 | vector twoSum(vector& numbers, int target) { 25 | vector res; 26 | int left = 0, right = numbers.size() - 1; 27 | while (1) { 28 | if (numbers[left] + numbers[right] > target) right--; 29 | else if (numbers[left] + numbers[right] < target) left++; 30 | if (numbers[left] + numbers[right] == target) break; 31 | } 32 | res.push_back(left + 1); 33 | res.push_back(right + 1); 34 | return res; 35 | } 36 | }; 37 | 38 | int main() { 39 | Solution s; 40 | Examples eg; 41 | } 42 | -------------------------------------------------------------------------------- /c++/168_Excel_Sheet_Column_Title.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | /*Given a positive integer, return its corresponding column title as appear in an Excel sheet. 18 | 19 | For example: 20 | 21 | 1 -> A 22 | 2 -> B 23 | 3 -> C 24 | ... 25 | 26 -> Z 26 | 27 -> AA 27 | 28 -> AB */ 28 | 29 | class Solution { 30 | public: 31 | string convertToTitle(int n) { 32 | string res; 33 | while (n > 0) { 34 | char ch = (n - 1) % 26 + 'A'; 35 | res = ch + res; // take care of order 36 | n = (n - 1) / 26; // remember to change to 0 based 37 | } 38 | return res; 39 | } 40 | }; 41 | 42 | 43 | int main() { 44 | Solution s; 45 | Examples eg; 46 | cout << s.convertToTitle(52) << endl; 47 | } 48 | -------------------------------------------------------------------------------- /c++/171_Excel_Sheet_Column_Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | /* A -> 1 17 | B -> 2 18 | C -> 3 19 | ... 20 | Z -> 26 21 | AA -> 27 22 | AB -> 28 */ 23 | 24 | class Solution { 25 | public: 26 | int titleToNumber(string s) { 27 | int sum = 0; 28 | for (auto c: s) { 29 | sum = sum * 26 + (c - 'A' + 1); 30 | } 31 | return sum; 32 | } 33 | }; 34 | 35 | 36 | int main() { 37 | Solution s; 38 | Examples eg; 39 | } 40 | -------------------------------------------------------------------------------- /c++/172_Factorial_Trailing_Zeroes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | /*Given an integer n, return the number of trailing zeroes in n! 15 | Note: Your solution should be in logarithmic time complexity.*/ 16 | 17 | class Solution { 18 | public: 19 | int trailingZeroes(int n) { 20 | int pow = log(n) / log(5); 21 | int sum = 0, div = 5; 22 | while (pow-- > 0) { 23 | sum += n / div; 24 | div *= 5; 25 | } 26 | return sum; 27 | } 28 | }; 29 | 30 | int main() { 31 | Solution s; 32 | Examples eg; 33 | cout << s.trailingZeroes(50) << endl; 34 | } 35 | -------------------------------------------------------------------------------- /c++/189_Rotate_Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | 15 | class Solution { 16 | public: 17 | void rotate(vector& nums, int k) { 18 | if (k <= 0) return; 19 | while (k-- > 0) { 20 | int tmp = nums.back(); 21 | nums.erase(nums.end() - 1); 22 | nums.insert(nums.begin(), tmp); 23 | } 24 | 25 | } 26 | }; 27 | 28 | int main() { 29 | Solution s; 30 | Examples eg; 31 | int tmp[] = {1,2,3,4,5,6,7}; 32 | vector vec(tmp, tmp + 7); 33 | s.rotate(vec, 3); 34 | print1dVector(vec); 35 | } 36 | -------------------------------------------------------------------------------- /c++/190_Reverse_Bits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "000_basic.cpp" 15 | 16 | using namespace std; 17 | 18 | /*Reverse bits of a given 32 bits unsigned integer. 19 | 20 | For example, given input 43261596 return 964176192 21 | binary as 00000010100101000001111010011100 22 | 00111001011110000010100101000000 23 | 24 | Follow up: 25 | If this function is called many times, how would you optimize it?*/ 26 | 27 | class Solution { 28 | public: 29 | uint32_t reverseBits(uint32_t n) { 30 | uint32_t m = 0; 31 | for (int i = 0; i < 31; i++) { 32 | m |= (n & 1); // take the 1st loc as its 32th loc, 2nd .. as 31... 33 | n >>= 1; 34 | m <<= 1; 35 | } 36 | m |= (n & 1); 37 | return m; 38 | } 39 | }; 40 | 41 | 42 | int main() { 43 | Solution s; 44 | Examples eg; 45 | cout << s.reverseBits(1) << endl; 46 | } 47 | -------------------------------------------------------------------------------- /c++/191_Number_of_1_Bits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | int hammingWeight(uint32_t n) { 19 | int res = 0; 20 | while (n >= 1) { 21 | if (n % 2 == 1) res++; 22 | n /= 2; 23 | } 24 | return res; 25 | } 26 | }; 27 | 28 | 29 | int main() { 30 | Solution s; 31 | Examples eg; 32 | } 33 | -------------------------------------------------------------------------------- /c++/198_House_Robber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | int rob(vector& nums) { 19 | int n = nums.size(); 20 | if (n == 0) return 0; 21 | int dp[n+1] = {0}; 22 | dp[1] = nums[0]; 23 | for (int i = 2; i < n+1; i++) { 24 | dp[i] = max(dp[i-1], nums[i-1] + dp[i-2]); 25 | } 26 | return dp[n]; 27 | } 28 | }; 29 | 30 | 31 | int main() { 32 | Solution s; 33 | Examples eg; 34 | } 35 | -------------------------------------------------------------------------------- /c++/201_Bitwise_AND_of_Numbers_Range.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | /*Given a range [m, n] where 0 <= m <= n <= 2147483647, 18 | return the bitwise AND of all numbers in this range, inclusive. 19 | 20 | For example, given the range [5, 7], you should return 4.*/ 21 | 22 | 23 | /*this question is a little hard to understand. 24 | one explains here: https://discuss.leetcode.com/topic/20176/2-line-solution-with-detailed-explanation*/ 25 | 26 | class Solution { 27 | public: 28 | /*if n > m, the rightest digit is 0, we transform this question into subproblem*/ 29 | int rangeBitwiseAnd(int m, int n) { 30 | return (n > m) ? (rangeBitwiseAnd(m/2, n/2) << 1) : m; 31 | } 32 | }; 33 | 34 | 35 | int main() { 36 | Solution s; 37 | Examples eg; 38 | cout << s.rangeBitwiseAnd(100, 1000000000) << endl; 39 | } 40 | -------------------------------------------------------------------------------- /c++/202_Happy_Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | bool isHappy(int n) { 19 | int slow = n, fast = n; 20 | do { 21 | slow = squareSum(slow); 22 | fast = squareSum(squareSum(fast)); 23 | } while (slow != fast); 24 | if (slow == 1) return 1; 25 | else return 0; 26 | } 27 | 28 | int squareSum(int num) { 29 | int sum = 0; 30 | while (num) { 31 | sum += pow(num % 10, 2); 32 | num /= 10; 33 | } 34 | return sum; 35 | } 36 | }; 37 | 38 | 39 | int main() { 40 | Solution s; 41 | Examples eg; 42 | cout << s.isHappy(19) << endl; 43 | } 44 | -------------------------------------------------------------------------------- /c++/203_Remove_Linked_List_Elements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | /*Remove all elements from a linked list of integers that have value val. 18 | 19 | Example 20 | Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 21 | Return: 1 --> 2 --> 3 --> 4 --> 5*/ 22 | 23 | 24 | class Solution { 25 | public: 26 | ListNode* removeElements(ListNode* head, int val) { 27 | if (!head) return head; 28 | if (head->val == val) return removeElements(head->next, val); 29 | ListNode* p = head; 30 | while (p->next) { 31 | if (p->next->val == val) p->next = p->next->next; 32 | else p = p->next; 33 | } 34 | return head; 35 | } 36 | }; 37 | 38 | 39 | int main() { 40 | Solution s; 41 | Examples eg; 42 | } 43 | -------------------------------------------------------------------------------- /c++/204_Count_Primes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | /* Count the number of prime numbers less than a non-negative number, n. 18 | // iterate all the 4, 6, 8 10 12 ... 30 19 | 9 12 15 18 21 ... 30 20 | 25 30 21 | 10 */ 22 | 23 | class Solution { 24 | public: 25 | int countPrimes(int n) { 26 | vector prime(n, true); 27 | prime[0] = false, prime[1] = false; 28 | for (int i = 2; i < sqrt(n); ++i) { 29 | if (prime[i]) { 30 | for (int j = i*i; j < n; j += i) { 31 | prime[j] = false; 32 | // cout << j << " " << prime[j] << " "; 33 | } 34 | // cout << endl; 35 | } 36 | } 37 | return count(prime.begin(), prime.end(), true); 38 | } 39 | }; 40 | 41 | int main() { 42 | Solution s; 43 | Examples eg; 44 | cout << s.countPrimes(31) << endl; 45 | } 46 | -------------------------------------------------------------------------------- /c++/217_Contains_Duplicate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | bool containsDuplicate(vector& nums) { 19 | unordered_set s; 20 | for (auto c : nums) { 21 | if (s.count(c) == 0) s.insert(c); 22 | else return true; 23 | } 24 | return false; 25 | } 26 | }; 27 | 28 | 29 | int main() { 30 | Solution s; 31 | Examples eg; 32 | } 33 | -------------------------------------------------------------------------------- /c++/231_Power_of_Two.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | // Given an integer, write a function to determine if it is a power of two. 18 | 19 | class Solution { 20 | public: 21 | bool isPowerOfTwo(int n) { 22 | if (n == 1) return true; 23 | if (n <= 0 || n % 2 != 0) return false; 24 | return isPowerOfTwo(n / 2); 25 | } 26 | }; 27 | 28 | class Solution { 29 | public: 30 | // if n = 10000, then n & (n - 1) = 0 31 | bool isPowerOfTwo(int n) { 32 | if (n <= 0) return false; 33 | return !(n & (n - 1)); 34 | } 35 | }; 36 | 37 | 38 | int main() { 39 | Solution s; 40 | Examples eg; 41 | } 42 | -------------------------------------------------------------------------------- /c++/237_Delete_Node_in_a_Linked_List.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | 17 | /*Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with 18 | value 3, the linked list should become 1 -> 2 -> 4 after calling your function.*/ 19 | 20 | class Solution { 21 | public: 22 | void deleteNode2(ListNode* node) { // failed version 23 | auto temp = node; 24 | *node = *temp->next; 25 | cout << node << endl; 26 | delete temp; // this delete didn't point a right next node 27 | cout << node << endl; 28 | } 29 | void deleteNode(ListNode* node) { // success version 30 | auto temp = node->next; 31 | *node = *temp; 32 | delete temp; 33 | } 34 | }; 35 | 36 | int main() { 37 | Solution s; 38 | ListNode* node1 = new ListNode(1); 39 | ListNode* node2 = new ListNode(2); 40 | ListNode* node3 = new ListNode(3); 41 | node1->next = node2; 42 | node2->next = node3; 43 | s.deleteNode2(node2); 44 | cout << node1->next->val << endl; 45 | } 46 | -------------------------------------------------------------------------------- /c++/238_Product_of_Array_Except_Self.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | vector productExceptSelf(vector& nums) { 19 | vector out; 20 | int p = 1; 21 | for (int i = 0; i < nums.size(); i++) { 22 | out.push_back(p); 23 | p *= nums[i]; 24 | } 25 | p = 1; 26 | for (int i = nums.size() - 1; i > -1; i--) { 27 | out[i] *= p; 28 | p *= nums[i]; 29 | } 30 | return out; 31 | } 32 | }; 33 | 34 | 35 | 36 | int main() { 37 | Solution s; 38 | Examples eg; 39 | } 40 | -------------------------------------------------------------------------------- /c++/258_Add_Digits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | int addDigits(int num) { 19 | while (num >= 10) { 20 | int sum = 0; 21 | while (num) { 22 | sum += num % 10; 23 | num /= 10; 24 | } 25 | num = sum; 26 | } 27 | return num; 28 | } 29 | }; 30 | 31 | 32 | int main() { 33 | Solution s; 34 | Examples eg; 35 | } 36 | -------------------------------------------------------------------------------- /c++/263_Ugly_Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | /*Write a program to check whether a given number is an ugly number. 18 | 19 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 20 | For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 21 | 22 | Note that 1 is typically treated as an ugly number.*/ 23 | 24 | class Solution { 25 | public: 26 | bool isUgly(int num) { 27 | if (num == 0) return false; 28 | if (num % 5 == 0) return isUgly(num / 5); 29 | if (num % 3 == 0) return isUgly(num / 3); 30 | if (num % 2 == 0) return isUgly(num / 2); 31 | return num == 1; 32 | } 33 | }; 34 | 35 | 36 | int main() { 37 | Solution s; 38 | Examples eg; 39 | cout << s.isUgly(0) << endl; 40 | } 41 | -------------------------------------------------------------------------------- /c++/266_Palindrome_Permutation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | /* 15 | Given a string, determine if a permutation of the string could form a palindrome. 16 | 17 | For example, 18 | "code" -> False, "aab" -> True, "carerac" -> True.*/ 19 | 20 | class Solution { 21 | public: 22 | bool canPermutePalindrome(string s) { 23 | if (s.empty()) return false; 24 | int dt[256] = {0}; 25 | for (auto par : s) dt[par - '0'] += 1; 26 | int tag = 0; 27 | for (auto &c : dt) { 28 | if (c % 2 == 1) tag++; 29 | } 30 | if (tag > 1) return false; 31 | if (tag == 1) return s.size() % 2 == 1; 32 | return true; 33 | } 34 | }; 35 | 36 | 37 | int main() { 38 | Solution s; 39 | Examples eg; 40 | cout << s.canPermutePalindrome("aab") << endl; 41 | } 42 | -------------------------------------------------------------------------------- /c++/268_Missing_Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "func.cpp" 12 | 13 | using namespace std; 14 | 15 | class Solution { 16 | public: 17 | int missingNumber(vector& nums) { 18 | int sum = 0; 19 | for (auto i : nums) 20 | sum += i; 21 | int n = nums.size(); 22 | return n * (n + 1) / 2 - sum; 23 | } 24 | }; 25 | 26 | class Solution2 { // if nums is sorted 27 | public: 28 | int missingNumber(vector& nums) { 29 | sort(nums.begin(), nums.end()); 30 | int left = 0, right = nums.size(); 31 | while (left < right) { 32 | int mid = left + (right - left) / 2; 33 | if (nums[mid] > mid) right = mid; 34 | else left = mid + 1; 35 | } 36 | return right; 37 | } 38 | }; 39 | 40 | int main() { 41 | Solution s; 42 | Examples eg; 43 | } 44 | -------------------------------------------------------------------------------- /c++/274_H-Index.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "func.cpp" 12 | 13 | using namespace std; 14 | 15 | class Solution { 16 | public: 17 | int hIndex(vector& citations) { 18 | int len = citations.size(); 19 | if (!len) return 0; 20 | sort(citations.begin(), citations.end()); 21 | 22 | //print1dVector(citations); 23 | for (int i = 0; i < citations.size(); i++) { 24 | //cout << citations[i] << " " << len << endl; 25 | if (citations[i] >= len) 26 | break; 27 | len--; 28 | } 29 | return len; 30 | } 31 | }; 32 | 33 | 34 | int main() { 35 | Solution s; 36 | Examples eg; 37 | int dat[] = {2,0,6,1,5}; 38 | vector citations(dat, dat+sizeof(dat)/sizeof(int)); 39 | cout << s.hIndex(citations) << endl; 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /c++/275_H-Index_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "func.cpp" 12 | 13 | using namespace std; 14 | 15 | 16 | class Solution { 17 | public: 18 | int hIndex(vector& citations) { 19 | int len = citations.size(); 20 | if (!len) return 0; 21 | for (int i = 0; i < citations.size(); i++) { 22 | if (citations[i] >= len) 23 | break; 24 | len--; 25 | } 26 | return len; 27 | } 28 | }; 29 | 30 | int main() { 31 | Solution s; 32 | Examples eg; 33 | } 34 | -------------------------------------------------------------------------------- /c++/279_Perfect_Squares.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | /*Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. 18 | 19 | For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.*/ 20 | 21 | class Solution { 22 | public: 23 | int numSquares(int n) { 24 | // about why to use static : https://discuss.leetcode.com/topic/23812/static-dp-c-12-ms-python-172-ms-ruby-384-ms 25 | // only is initialized once, but is it kind of like cheating? 26 | static vector dp = {0}; // dp[i] represents the minimum number of square numbers that sum to i 27 | 28 | while (dp.size() <= n) { 29 | int cntNum = INT_MAX; 30 | int size = dp.size(); 31 | for (int i = 1; i * i <= size; i++) { 32 | cntNum = min(cntNum, dp[size - i * i] + 1); 33 | } 34 | dp.push_back(cntNum); 35 | } 36 | return dp[n]; 37 | } 38 | }; 39 | 40 | 41 | int main() { 42 | Solution s; 43 | Examples eg; 44 | } 45 | -------------------------------------------------------------------------------- /c++/292_Nim_Game.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | // math logic here 17 | // anyone who can leave the opponent 4 can win. 18 | // e.g. n = 7, you remove 3, then only 4 left, no matter how many steps you opponent choose, you win 19 | // to generalize, if n = 9, you take 1, then 8 left, no matter how many steps your opponent choose, you can leave 4. 20 | // if n = 13, you take 1, 12 left, then choose 8 left, ... 21 | class Solution { 22 | public: 23 | bool canWinNim(int n) { 24 | if (n % 4 == 0) return false; 25 | return true; 26 | } 27 | }; 28 | 29 | int main() { 30 | Solution s; 31 | Examples eg; 32 | } 33 | -------------------------------------------------------------------------------- /c++/299_Bulls_and_Cows.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | 18 | class Solution { 19 | public: 20 | string getHint(string secret, string guess) { 21 | int bulls(0), cows(0), cnt[10] = {0}; 22 | for (int i = 0; i < secret.size(); i++) { 23 | if (secret[i] == guess[i]) bulls++; 24 | else cnt[secret[i] - '0']++; 25 | } 26 | for (int i = 0; i < guess.size(); i++) { 27 | if (secret[i] == guess[i]) continue; 28 | if (cnt[guess[i] - '0'] > 0) { 29 | cnt[guess[i] - '0'] -= 1; 30 | cows++; 31 | } 32 | } 33 | return to_string(bulls) + 'A' + to_string(cows) + 'B'; 34 | } 35 | }; 36 | 37 | int main() { 38 | Solution s; 39 | Examples eg; 40 | cout << s.getHint("1807", "7810") << endl; 41 | } 42 | -------------------------------------------------------------------------------- /c++/303_Range_Sum_Query_-_Immutable.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "000_basic.cpp" 14 | 15 | using namespace std; 16 | 17 | /*Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 18 | 19 | Example: 20 | Given nums = [-2, 0, 3, -5, 2, -1] 21 | 22 | sumRange(0, 2) -> 1 23 | sumRange(2, 5) -> -1 24 | sumRange(0, 5) -> -3 25 | Note: 26 | You may assume that the array does not change. 27 | There are many calls to sumRange function.*/ 28 | 29 | 30 | class NumArray { 31 | public: 32 | NumArray(vector &nums) { 33 | dp.push_back(0); 34 | for (int i = 0; i < nums.size(); i++) { 35 | dp.push_back(dp.back() + nums[i]); 36 | } 37 | } 38 | 39 | int sumRange(int i, int j) { 40 | return dp[j + 1] - dp[i]; 41 | } 42 | private: 43 | vector dp; 44 | }; 45 | 46 | 47 | 48 | int main() { 49 | Solution s; 50 | Examples eg; 51 | } 52 | -------------------------------------------------------------------------------- /c++/319_Bulb_Switcher.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | /* bulbs ends up on iff it is switched an odd times 17 | if not a square, it must be switched even times 18 | since 15 = 3 * 5 = 5 * 3, every factorization have a pair 19 | */ 20 | 21 | class Solution { 22 | public: 23 | int bulbSwitch(int n) { 24 | return sqrt(n); 25 | } 26 | }; 27 | 28 | 29 | int main() { 30 | Solution s; 31 | Examples eg; 32 | } 33 | -------------------------------------------------------------------------------- /c++/326_Power_of_Three.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | bool isPowerOfThree(int n) { 19 | if (n <= 0) return false; 20 | int divisor = pow(3, (int)(log(INT_MAX) / log(3))); 21 | return divisor % n == 0; 22 | } 23 | }; 24 | 25 | int main() { 26 | Solution s; 27 | Examples eg; 28 | cout << s.isPowerOfThree(81) << endl; 29 | } 30 | -------------------------------------------------------------------------------- /c++/334_Increasing_Triplet_Subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include "000_basic.cpp" 17 | 18 | using namespace std; 19 | 20 | /*Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. 21 | 22 | Formally the function should: 23 | Return true if there exists i, j, k 24 | such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. 25 | Your algorithm should run in O(n) time complexity and O(1) space complexity. 26 | 27 | Examples: 28 | Given [1, 2, 3, 4, 5], 29 | return true. 30 | 31 | Given [5, 4, 3, 2, 1], 32 | return false.*/ 33 | 34 | class Solution { 35 | public: 36 | bool increasingTriplet(vector& nums) { 37 | int c1 = INT_MAX, c2 = INT_MAX; 38 | for (auto i: nums) { 39 | if (i <= c1) c1 = i; // tag the smallest number 40 | else if (i <= c2) c2 = i; // tag the second smallest number 41 | else return true; // the third smallest number appears 42 | } 43 | return false; 44 | } 45 | }; 46 | 47 | 48 | int main() { 49 | Solution s; 50 | Examples eg; 51 | } 52 | -------------------------------------------------------------------------------- /c++/342_Power_of_Four.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "000_basic.cpp" 15 | 16 | using namespace std; 17 | 18 | /*Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 19 | 20 | Example: 21 | Given num = 16, return true. Given num = 5, return false. 22 | 23 | Follow up: Could you solve it without loops/recursion?*/ 24 | 25 | class Solution { 26 | public: 27 | bool isPowerOfFour(int num) { 28 | int cmp = 1, bak = num; 29 | while (bak > 1) { 30 | bak >>= 2; 31 | cmp <<= 2; 32 | } 33 | return cmp == num; 34 | } 35 | }; 36 | 37 | class Solution { 38 | public: 39 | bool isPowerOfFour(int num) { 40 | return (num > 0) && (num & (num - 1)) == 0 && (num - 1) % 3 == 0; 41 | } 42 | }; 43 | 44 | 45 | int main() { 46 | Solution s; 47 | Examples eg; 48 | cout << s.isPowerOfFour(15) << endl; 49 | } 50 | -------------------------------------------------------------------------------- /c++/344_Reverse_String.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | 15 | class Solution { 16 | public: 17 | string reverseString(string s) { 18 | for (int i = 0; i < s.size() / 2; i++) { 19 | char tmp = s[i]; 20 | s[i] = s[s.size() - i - 1]; 21 | s[s.size() - i - 1] = tmp; 22 | } 23 | return s; 24 | } 25 | }; 26 | 27 | int main() { 28 | Solution s; 29 | Examples eg; 30 | } 31 | -------------------------------------------------------------------------------- /c++/349_Intersection_of_Two_Arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "000_basic.cpp" 15 | 16 | using namespace std; 17 | 18 | /*Given two arrays, write a function to compute their intersection. 19 | 20 | Example: 21 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 22 | 23 | Note: 24 | Each element in the result must be unique. 25 | The result can be in any order.*/ 26 | 27 | class Solution { 28 | public: 29 | vector intersection(vector& nums1, vector& nums2) { 30 | unordered_set st1, st2; 31 | for (auto c: nums1) st1.insert(c); 32 | vector vec; 33 | for (auto c: nums2) if (st1.count(c) > 0) st2.insert(c); 34 | for (auto c: st2) vec.push_back(c); 35 | return vec; 36 | } 37 | }; 38 | 39 | 40 | int main() { 41 | Solution s; 42 | Examples eg; 43 | vector nums1 = {1,2,2,1}, nums2 = {2,2}; 44 | print(s.intersection(nums1, nums2)); 45 | } 46 | -------------------------------------------------------------------------------- /c++/350_Intersection_of_Two_Arrays_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "000_basic.cpp" 15 | 16 | using namespace std; 17 | 18 | /*Given two arrays, write a function to compute their intersection. 19 | 20 | Example: 21 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. 22 | 23 | Note: 24 | Each element in the result should appear as many times as it shows in both arrays. 25 | The result can be in any order.*/ 26 | 27 | class Solution { 28 | public: 29 | vector intersect(vector& nums1, vector& nums2) { 30 | // if (nums2.size() > nums1.size()) return intersect(nums2, nums1); 31 | unordered_map mp; 32 | for (auto c: nums1) mp[c]++; 33 | vector vec; 34 | for (auto c: nums2) { 35 | if (mp[c] > 0) { 36 | vec.push_back(c); 37 | mp[c]--; 38 | } 39 | } 40 | return vec; 41 | } 42 | }; 43 | 44 | 45 | 46 | int main() { 47 | Solution s; 48 | Examples eg; 49 | vector nums1 = {1,2}, nums2 = {1,1}; 50 | print(s.intersect(nums1, nums2)); 51 | } 52 | -------------------------------------------------------------------------------- /c++/357_Count_Numbers_with_Unique_Digits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include "000_basic.cpp" 17 | 18 | using namespace std; 19 | 20 | class Solution { 21 | public: 22 | int countNumbersWithUniqueDigits(int n) { 23 | if (n == 0) return 1; 24 | if (n == 1) return 10; 25 | vector dp(10, 0); 26 | dp[1] = 10; 27 | int sum = 0; 28 | for (int i = 2; i <= min(n, 10); i++) { 29 | dp[i] = 9; 30 | int j = i, k = 9; 31 | while (j-- > 1) { 32 | dp[i] *= k--; 33 | } 34 | dp[i] += dp[i-1]; 35 | } 36 | return n > 10? dp[10]: dp[n]; 37 | } 38 | }; 39 | 40 | 41 | int main() { 42 | Solution s; 43 | Examples eg; 44 | cout << s.countNumbersWithUniqueDigits(3) << endl; 45 | } 46 | -------------------------------------------------------------------------------- /c++/367_Valid_Perfect_Square.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include "000_basic.cpp" 17 | 18 | using namespace std; 19 | 20 | /*Given a positive integer num, write a function which returns True if num is a perfect square else False. 21 | 22 | Note: Do not use any built-in library function such as sqrt. 23 | 24 | Example 1: 25 | 26 | Input: 16 27 | Returns: True 28 | Example 2: 29 | 30 | Input: 14 31 | Returns: False*/ 32 | 33 | class Solution { 34 | public: 35 | bool isPerfectSquare(int num) { 36 | int l = 1, r = num; 37 | long long mid; 38 | while (l <= r) { 39 | mid = l + (r - l) / 2; 40 | cout << l << " " << mid << " " << r << endl; 41 | if (mid * mid == num) return true; 42 | else if (mid * mid > num) r = mid - 1; 43 | else l = mid + 1; 44 | } 45 | return false; 46 | } 47 | }; 48 | 49 | int main() { 50 | Solution s; 51 | Examples eg; 52 | cout << s.isPerfectSquare(104976) << endl; 53 | } 54 | -------------------------------------------------------------------------------- /c++/371_Sum_of_Two_Integers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | /* 17 | 1101 18 | + 0101 19 | = 10010 20 | 21 | a^b = 1000 22 | a&b<1= 1010 23 | 24 | a^b = 10 25 | a&b<1=10000 26 | 27 | a^b =10010 28 | a&b<1= 0 29 | 30 | sum = 10010 31 | 32 | In summary, 33 | ^ takes the unique digit that does not have carry potential 34 | skip 0 vs 0, 1 vs 1, only consider 0 vs 1 and 1 vs 0 35 | & takes the same 1 and get the function of multiplication 36 | only consider 1 vs 1, if multiply by 2 when it occurs to us 37 | 38 | 39 | Another question is that why in this code, it only considers the terminating case of b==0 40 | In fact, 41 | if we sum 42 | 111 43 | 111 44 | 45 | a^b 000 46 | a&b 1110 47 | 48 | a^b 1110 49 | a&b 0 50 | 51 | sum = 1110 52 | */ 53 | class Solution { 54 | public: 55 | int getSum(int a, int b) { 56 | return b==0? a: getSum(a^b, (a&b)<<1); //be careful about the terminating condition; 57 | } 58 | }; 59 | 60 | int main() { 61 | Solution s; 62 | Examples eg; 63 | cout << s.count_one(7) << endl; 64 | } 65 | -------------------------------------------------------------------------------- /c++/383_Ransom_Note.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "000_basic.cpp" 15 | 16 | using namespace std; 17 | 18 | /*Given an arbitrary ransom note string and another string containing letters from 19 | all the magazines, write a function that will return true if the ransom note can be 20 | constructed from the magazines ; otherwise, it will return false. 21 | 22 | Each letter in the magazine string can only be used once in your ransom note. 23 | 24 | Note: 25 | You may assume that both strings contain only lowercase letters. 26 | 27 | canConstruct("a", "b") -> false 28 | canConstruct("aa", "ab") -> false 29 | canConstruct("aa", "aab") -> true*/ 30 | 31 | class Solution { 32 | public: 33 | bool canConstruct(string ransomNote, string magazine) { 34 | int dp[26] = {0}; 35 | for (auto c: magazine) dp[c - 'a']++; 36 | for (auto c: ransomNote) if (--dp[c - 'a'] < 0) return false; 37 | return true; 38 | } 39 | }; 40 | 41 | 42 | int main() { 43 | Solution s; 44 | Examples eg; 45 | cout << s.canConstruct("aa", "aab") << endl; 46 | } 47 | -------------------------------------------------------------------------------- /c++/386_Lexicographical_Numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | 15 | /* brilliant idea: regard the digits as a tree, use preorder to traverse 16 | 1 2 3 4 17 | / \ / \ / \ / \ 18 | 10 .. 20 21 22 ..... 19 | / \ 20 | 100 .... 21 | Don't try to build the tree yourself, just think of the numbers as a 10-tree*/ 22 | 23 | class Solution { 24 | public: 25 | vector lexicalOrder(int n) { 26 | vector res; 27 | for (int i = 1; i < 10; i++) 28 | dfs(i, n, res); 29 | return res; 30 | } 31 | void dfs(int cur, int n, vector &res) { 32 | if (cur <= n) { 33 | res.push_back(cur); 34 | for (int i = 0; i < 10; i++) 35 | dfs(10 * cur + i, n, res); 36 | } 37 | else return; 38 | } 39 | }; 40 | 41 | 42 | int main() { 43 | Solution s; 44 | Examples eg; 45 | vector res = s.lexicalOrder(1123); 46 | print1dVector(res); 47 | } 48 | -------------------------------------------------------------------------------- /c++/387_First_Unique_Character_in_a_String.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "func.cpp" 11 | 12 | using namespace std; 13 | 14 | class Solution_slow { 15 | public: 16 | int firstUniqChar(string s) { 17 | int n = s.size(); 18 | if (!n) return -1; 19 | unordered_map dt; 20 | for (int i = 0; i < n; i++) { 21 | if (dt.count(s[i]) == 0) 22 | dt[s[i]] = 1; 23 | else 24 | dt[s[i]]++; 25 | } 26 | for (int i = 0; i < n; i++) { 27 | if (dt[s[i]] == 1) 28 | return i; 29 | } 30 | return -1; 31 | } 32 | }; 33 | 34 | 35 | class Solution { 36 | public: 37 | int firstUniqChar(string s) { 38 | int n = s.size(); 39 | if (!n) return -1; 40 | int dt[26] = {0}; 41 | for (int i = 0; i < n; i++) 42 | dt[s[i] - 'a']++; 43 | for (int i = 0; i < n; i++) { 44 | if (dt[s[i] - 'a'] == 1) 45 | return i; 46 | } 47 | } 48 | }; 49 | 50 | int main() { 51 | Solution s; 52 | Examples eg; 53 | } 54 | -------------------------------------------------------------------------------- /c++/404_Sum_of_Left_Leaves.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "000_basic.cpp" 16 | 17 | using namespace std; 18 | 19 | /*Find the sum of all left leaves in a given binary tree. 20 | 21 | Example: 22 | 23 | 3 24 | / \ 25 | 9 20 26 | / \ 27 | 15 7 28 | 29 | There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.*/ 30 | 31 | 32 | class Solution { 33 | public: 34 | int sumOfLeftLeaves(TreeNode* root) { 35 | if (!root) return 0; 36 | return dfs(root, false); 37 | } 38 | int dfs(TreeNode* root, bool ifLeft) { 39 | if (root && !root->left && !root->right) { 40 | if (ifLeft) return root->val; 41 | else return 0; 42 | } 43 | int sum = 0, vleft = 0, vright = 0; 44 | if (root->left) vleft = dfs(root->left, true); 45 | if (root->right) vright = dfs(root->right, false); 46 | return sum + vleft + vright; 47 | } 48 | }; 49 | 50 | 51 | int main() { 52 | Solution s; 53 | Examples eg; 54 | 55 | } 56 | -------------------------------------------------------------------------------- /c++/412_Fizz_Buzz.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "000_basic.cpp" 13 | 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | vector fizzBuzz(int n) { 19 | vector res; 20 | for (int i = 1; i <= n; i++) { 21 | if (i % 15 == 0) res.push_back("FizzBuzz"); 22 | else if (i % 3 == 0) res.push_back("Fizz"); 23 | else if (i % 5 == 0) res.push_back("Buzz"); 24 | else res.push_back(to_string(i)); 25 | } 26 | return res; 27 | } 28 | }; 29 | 30 | 31 | int main() { 32 | Solution s; 33 | Examples eg; 34 | } 35 | -------------------------------------------------------------------------------- /c++/414_Third_Maximum_Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "000_basic.cpp" 16 | 17 | using namespace std; 18 | 19 | 20 | class Solution { 21 | public: 22 | int thirdMax(vector& nums) { 23 | priority_queue pq(nums.begin(), nums.end()); 24 | if (nums.size() < 3) return pq.top(); 25 | stack stk; 26 | while (!pq.empty()) { 27 | if (stk.empty() || stk.top() != pq.top()) stk.push(pq.top()); 28 | pq.top(); 29 | if (stk.size() == 3 || pq.empty()); 30 | } 31 | } 32 | }; 33 | 34 | int main() { 35 | Solution s; 36 | Examples eg; 37 | } 38 | -------------------------------------------------------------------------------- /c++/415_Add_Strings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "000_basic.cpp" 16 | 17 | using namespace std; 18 | 19 | class Solution { 20 | public: 21 | string addStrings(string num1, string num2) { 22 | int i = num1.size() - 1; 23 | int j = num2.size() - 1; 24 | int carry = 0; 25 | string res = ""; 26 | while (i >= 0 || j >= 0 || carry) { 27 | int sum = 0; 28 | sum += (i >= 0? num1[i--] - '0': 0); // very consise idea 29 | sum += (j >= 0? num2[j--] - '0': 0) + carry; 30 | carry = sum / 10; 31 | res = to_string(sum % 10) + res; 32 | } 33 | return res; 34 | } 35 | }; 36 | 37 | 38 | int main() { 39 | Solution s; 40 | Examples eg; 41 | } 42 | -------------------------------------------------------------------------------- /c++/434_Number_of_Segments_in_a_String.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "000_basic.cpp" 16 | 17 | using namespace std; 18 | 19 | /*Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. 20 | 21 | Please note that the string does not contain any non-printable characters. 22 | 23 | Example: 24 | 25 | Input: "Hello, my name is John" 26 | Output: 5*/ 27 | 28 | class Solution { 29 | public: 30 | int countSegments_a_little_slow(string s) { 31 | stringstream ss(s); 32 | int cnt = 0; 33 | string tmp; 34 | while (ss >> tmp) { 35 | cnt++; 36 | cout << ss.str() << endl; 37 | } 38 | return cnt; 39 | } 40 | 41 | int countSegments(string s) { 42 | int res = 0; 43 | for (int i = 0; i < s.size(); i++) 44 | res += s[i] != ' ' && (i + 1 == s.size() || s[i+1] == ' '); 45 | return res; 46 | } 47 | }; 48 | 49 | 50 | int main() { 51 | Solution s; 52 | Examples eg; 53 | cout << s.countSegments("a b c") << endl; 54 | } 55 | -------------------------------------------------------------------------------- /c++/453_Minimum_Moves_to_Equal_Array_Elements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "000_basic.cpp" 16 | 17 | using namespace std; 18 | 19 | /*Given a non-empty integer array of size n, find the minimum number of moves required to 20 | make all array elements equal, where a move is incrementing n - 1 elements by 1. 21 | 22 | Example: 23 | 24 | Input: 25 | [1,2,3] 26 | 27 | Output: 28 | 3 29 | 30 | Explanation: 31 | Only three moves are needed (remember each move increments two elements): 32 | 33 | [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]*/ 34 | 35 | class Solution { 36 | public: 37 | int minMoves(vector& nums) { 38 | int minv = INT_MAX, res = 0; 39 | for (auto n: nums) minv = min(minv, n); 40 | for (auto n: nums) res += n - minv; 41 | return res; 42 | } 43 | }; 44 | 45 | 46 | int main() { 47 | Solution s; 48 | Examples eg; 49 | } 50 | -------------------------------------------------------------------------------- /c++/461_Hamming_Distance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "000_basic.cpp" 16 | 17 | using namespace std; 18 | 19 | /*The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 20 | 21 | Given two integers x and y, calculate the Hamming distance. 22 | 23 | Note: 24 | 0 ≤ x, y < 231. 25 | 26 | Example: 27 | 28 | Input: x = 1, y = 4 29 | 30 | Output: 2 31 | 32 | Explanation: 33 | 1 (0 0 0 1) 34 | 4 (0 1 0 0) 35 | ↑ ↑ 36 | 37 | The above arrows point to positions where the corresponding bits are different.*/ 38 | 39 | class Solution { 40 | public: 41 | int hammingDistance(int x, int y) { 42 | int res = 0, i = 0; 43 | while (i++ < 32) { 44 | res += (x & 1) ^ (y & 1); 45 | x >>= 1; 46 | y >>= 1; 47 | cout << x << " " << y << endl; 48 | } 49 | return res; 50 | } 51 | }; 52 | 53 | 54 | int main() { 55 | Solution s; 56 | Examples eg; 57 | cout << s.hammingDistance(1, 4) << endl; 58 | } 59 | -------------------------------------------------------------------------------- /c++/485_Max_Consecutive_Ones.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "000_basic.cpp" 16 | 17 | using namespace std; 18 | 19 | /*Given a binary array, find the maximum number of consecutive 1s in this array. 20 | 21 | Example 1: 22 | Input: [1,1,0,1,1,1] 23 | Output: 3 24 | Explanation: The first two digits or the last three digits are consecutive 1s. 25 | The maximum number of consecutive 1s is 3. 26 | Note: 27 | 28 | The input array will only contain 0 and 1. 29 | The length of input array is a positive integer and will not exceed 10,000*/ 30 | 31 | class Solution { 32 | public: 33 | int findMaxConsecutiveOnes(vector& nums) { 34 | int maxV = 0, curMax = 0; 35 | for (auto i: nums) { 36 | curMax = (i ? curMax + 1: 0); 37 | maxV = max(curMax, maxV); 38 | } 39 | return maxV; 40 | } 41 | }; 42 | 43 | int main() { 44 | Solution s; 45 | Examples eg; 46 | } 47 | -------------------------------------------------------------------------------- /c++/500_keyboard_row.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | class Solution { 6 | public: 7 | vector findWords(vector& words) { 8 | 9 | std::unordered_set dict1 = { 'q','Q','w','W','e','E','r','R','t','T','y','Y','u','U','i','I','o','O','p','P' }; 10 | std::unordered_set dict2 = { 'a','A','s','S','d','D','f','F','g','G','h','H','j','J','k','K','l','L'}; 11 | std::unordered_set dict3 = { 'z','Z','x','X','c','C','v','V','b','B','n','N','m','M'}; 12 | 13 | vector res; 14 | 15 | for (auto &word : words) { 16 | bool d1 = true, d2 = true, d3 = true; 17 | for (auto & ch : word) { 18 | if (d1) { 19 | if (dict1.count(ch) == 0) d1 = false; 20 | } 21 | 22 | if (d2) { 23 | if (dict2.count(ch) == 0) d2 = false; 24 | } 25 | 26 | if (d3) { 27 | if (dict3.count(ch) == 0) d3 = false; 28 | } 29 | } 30 | 31 | if (d1 || d2 || d3) res.push_back(word); 32 | } 33 | 34 | return res; 35 | } 36 | }; -------------------------------------------------------------------------------- /c++/507_base_7.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "000_basic.cpp" 16 | 17 | using namespace std; 18 | 19 | class Solution { 20 | public: 21 | string convertToBase7(int num) { 22 | if (num == 0) return "0"; 23 | bool sign = true; 24 | if (num < 0) sign = false; 25 | string res = ""; 26 | num = abs(num); 27 | while (num) { 28 | res = to_string(num % 7) + res; 29 | num /= 7; 30 | } 31 | return sign? res: '-' + res; 32 | } 33 | }; -------------------------------------------------------------------------------- /c++/52_N-Queens_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int totalNQueens(int n) { 12 | vector cols; 13 | int allSol = 0; 14 | dfs(0, n, cols, allSol); 15 | return allSol; 16 | } 17 | 18 | void dfs(int irow, int n, vector cols, int &allSol) { 19 | if (irow == n) { 20 | allSol++; 21 | return; 22 | } 23 | for (int icol = 0; icol < n; icol++) { 24 | if (isValid(irow, icol, cols)) { 25 | cols.push_back(icol); 26 | dfs(irow + 1, n, cols, allSol); 27 | cols.pop_back(); 28 | } 29 | } 30 | 31 | } 32 | bool isValid(int irow, int icol, vector cols) { 33 | for (int row = 0; row < cols.size(); row++) { 34 | if (icol == cols[row] or abs(irow - row) == abs(icol - cols[row])) 35 | return false; 36 | } 37 | return true; 38 | } 39 | }; 40 | 41 | 42 | 43 | int main() { 44 | Solution s; 45 | } -------------------------------------------------------------------------------- /c++/55_Jump_Game.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | bool canJump(vector& nums) { 11 | int n = nums.size(), idx = 0; 12 | if (n <= 1) 13 | return true; 14 | for (int i = 0; i < n - 1; i++) { 15 | idx = max(idx, i + nums[i]); 16 | if (idx < i + 1) 17 | break; 18 | if (idx >= n - 1) 19 | return true; 20 | } 21 | return false; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /c++/58_Length_of_Last_Word.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | class Solution { 10 | public: 11 | int lengthOfLastWord(string s) { 12 | int n = s.size(); 13 | int tag = 1; 14 | int cnt = 0; 15 | for (int i = n - 1; i > -1; i--) { 16 | if (s[i] == ' ' and tag) 17 | continue; 18 | else if (s[i] != ' ' && tag) 19 | tag = 0; 20 | if (s[i] == ' ' && !tag) 21 | break; 22 | cnt++; 23 | } 24 | return cnt; 25 | } 26 | }; 27 | 28 | 29 | int main() { 30 | Solution s; 31 | cout << s.lengthOfLastWord("asd dsadasd sd ") << endl; 32 | } 33 | -------------------------------------------------------------------------------- /c++/59_Spiral_Matrix_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | 11 | class Solution { 12 | public: 13 | vector > generateMatrix(int n) { 14 | vector > res(n, vector(n)); // initialize 2-d vector 15 | 16 | int left = 0, top = 0; 17 | int right = n - 1, down = n - 1; 18 | int direction = 0; 19 | int number = 1; 20 | while (1) { 21 | if (direction == 0) { 22 | for (int i = left; i <= right; i++) 23 | res[top][i] = number++; 24 | top++; 25 | } 26 | if (direction == 1) { 27 | for (int i = top; i <= down; i++) 28 | res[i][right] = number++; 29 | right--; 30 | } 31 | if (direction == 2) { 32 | for (int i = right; i >= left; i--) 33 | res[down][i] = number++; 34 | down--; 35 | } 36 | if (direction == 3) { 37 | for (int i = down; i >= top; i--) 38 | res[i][left] = number++; 39 | left++; 40 | } 41 | if (number == pow(n, 2) + 1) 42 | break; 43 | direction = (direction + 1) % 4; 44 | } 45 | return res; 46 | } 47 | }; 48 | 49 | 50 | int main() { 51 | Solution s; 52 | vector > res = s.generateMatrix(3); 53 | 54 | } -------------------------------------------------------------------------------- /c++/60_Permutation_Sequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | string getPermutation(int n, int k) { 12 | int factorial = 1; 13 | for (int i = 1; i < n; i++) 14 | factorial *= i; 15 | k--; 16 | int sets[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 17 | vector setNum(sets, sets + 9); 18 | string res; 19 | int tag = 0; 20 | while (k >= 0 && tag < n) { 21 | tag++; 22 | int quotient = k / factorial; 23 | k -= quotient * factorial; 24 | res.push_back('0' + setNum[quotient]); 25 | setNum.erase(setNum.begin() + quotient); 26 | if (n == tag) 27 | factorial = 1; 28 | else 29 | factorial /= (n - tag); 30 | } 31 | return res; 32 | } 33 | }; 34 | 35 | int main() { 36 | Solution s; 37 | cout << s.getPermutation(2, 1) << endl; 38 | 39 | } -------------------------------------------------------------------------------- /c++/64_Minimum_Path_Sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int minPathSum(vector >& grid) { 12 | int m = grid.size(); 13 | int n = grid[0].size(); 14 | int dp[m][n] = {{0}}; 15 | if (m == 1 && n == 1) 16 | return grid[0][0]; 17 | dp[0][0] = grid[0][0]; 18 | for (int i = 0; i < m - 1; i++) 19 | dp[i + 1][0] = dp[i][0] + grid[i + 1][0]; 20 | for (int j = 0; j < n - 1; j++) 21 | dp[0][j + 1] = dp[0][j] + grid[0][j + 1]; 22 | for (int i = 0; i < m - 1; i++) 23 | for (int j = 0; j < n - 1; j++) 24 | dp[i + 1][j + 1] = min(dp[i + 1][j], dp[i][j + 1]) + grid[i + 1][j + 1]; 25 | return dp[m - 1][n - 1]; 26 | } 27 | }; 28 | 29 | 30 | int main() { 31 | Solution s; 32 | 33 | 34 | } -------------------------------------------------------------------------------- /c++/66_Plus_One.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector plusOne(vector& digits) { 11 | int n = digits.size(); 12 | int carry = 1; 13 | for (int i = n - 1; i >= 0; i--) { 14 | int sum = digits[i] + carry; 15 | carry = sum / 10; 16 | digits[i] = sum % 10; 17 | } 18 | if (carry) 19 | digits.insert(digits.begin(), 1); 20 | return digits; 21 | 22 | } 23 | }; 24 | 25 | 26 | int main() { 27 | 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /c++/67_Add_Binary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | string addBinary(string a, string b) { 12 | int m = a.size(); 13 | int n = b.size(); 14 | if (m < n) 15 | return addBinary(b, a); 16 | int total, carry = 0; 17 | string res; 18 | for (int i = 0; i < m; i++) { 19 | total = a[m - 1 - i] - '0' + carry; 20 | if (i < n) 21 | total += b[n - 1 - i] - '0'; 22 | cout << total << endl; 23 | carry = total / 2; 24 | res.push_back(total % 2 + '0'); 25 | } 26 | if (carry) 27 | res.push_back('1'); 28 | reverse(res.begin(), res.end()); 29 | return res; 30 | } 31 | }; 32 | 33 | 34 | int main() { 35 | Solution s; 36 | cout << s.addBinary("11", "1") << endl; 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /c++/70_Climbing_Stairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | class Solution { 10 | public: 11 | int climbStairs(int n) { 12 | if (n <= 2) 13 | return n; 14 | int dp[n + 1] = {0}; 15 | dp[1] = 1, dp[2] = 2; 16 | for (int i = 3; i <= n; i++) 17 | dp[i] = dp[i - 1] + dp[i - 2]; 18 | return dp[n]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /c++/71_Simplify_Path.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | string simplifyPath(string path) { 13 | string res, part; 14 | vector vec; 15 | path.push_back('/'); 16 | for (int i = 0; i < path.size(); i++) { 17 | if (path[i] != '/') 18 | part.push_back(path[i]); 19 | else if (path[i] == '/') { 20 | if (part.empty()) 21 | continue; 22 | else if (part == "..") { 23 | if (vec.empty()) { 24 | part.clear(); 25 | continue; 26 | } 27 | vec.pop_back(); 28 | } 29 | else if (part != ".") 30 | vec.push_back(part); 31 | part.clear(); 32 | } 33 | } 34 | 35 | for (int i = 0; i < vec.size(); i++) { 36 | res += "/" + vec[i]; 37 | } 38 | if (res.empty()) 39 | res = "/"; 40 | return res; 41 | } 42 | }; 43 | 44 | 45 | int main() { 46 | Solution s; 47 | cout << s.simplifyPath("/home/../../..") << endl; 48 | } -------------------------------------------------------------------------------- /c++/72_Edit_Distance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int minDistance(string word1, string word2) { 12 | int m = word1.size(), n = word2.size(); 13 | int dp[m+1][n+1] = {}; 14 | for(int i = 1; i < m + 1; i++) 15 | dp[i][0] = i; 16 | for(int i = 1; i < n + 1; i++) 17 | dp[0][i] = i; 18 | for(int i = 1; i < m + 1; i++) { 19 | for(int j = 1; j < n + 1; j++){ 20 | if (word1[i-1] == word2[j-1]) 21 | dp[i][j] = dp[i-1][j-1]; 22 | else 23 | dp[i][j] = min(min(dp[i-1][j-1], dp[i-1][j]), dp[i][j-1]) + 1; 24 | } 25 | } 26 | return dp[m][n]; 27 | } 28 | }; 29 | 30 | 31 | 32 | 33 | int main() { 34 | Solution s; 35 | cout << s.minDistance("a", "b") << endl; 36 | } -------------------------------------------------------------------------------- /c++/73_Set_Matrix_Zeroes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | void setZeroes(vector>& matrix) { 12 | int m = matrix.size(); 13 | int n = matrix[0].size(); 14 | int tagRow[m] = {0}; 15 | int tagCOl[n] = {0}; 16 | for (int i = 0; i < m; i++) { 17 | for (int j = 0; j < n; j++) { 18 | if (matrix[i][j] != 0) 19 | continue; 20 | tagRow[i] = 1; 21 | tagCOl[j] = 1; 22 | } 23 | } 24 | for (int i = 0; i < m; i++) 25 | for (int j = 0; j < n; j++) 26 | if (tagRow[i] || tagCOl[j]) 27 | matrix[i][j] = 0; 28 | } 29 | }; 30 | 31 | // there is actually a better way which uses o(1) space 32 | // the trick is to mark infos in the first row and col 33 | 34 | 35 | int main() { 36 | Solution s; 37 | } -------------------------------------------------------------------------------- /c++/74_Search_a_2D_Matrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | bool searchMatrix(vector>& matrix, int target) { 12 | int m = matrix.size(); 13 | int n = matrix[0].size(); 14 | int left = 0, right = m * n - 1; 15 | while (left <= right) { 16 | int mid = (left + right) / 2; 17 | int i = mid / n; 18 | int j = mid % n; 19 | if (matrix[i][j] == target) 20 | return true; 21 | else if (matrix[i][j] > target) 22 | right = mid - 1; 23 | else 24 | left = mid + 1; 25 | } 26 | return false; 27 | } 28 | }; 29 | 30 | 31 | int main() { 32 | Solution s; 33 | } -------------------------------------------------------------------------------- /c++/75_Sort_Colors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | void sortColors(vector& nums) { 12 | int n = nums.size(); 13 | int left = 0, right = n - 1, i = 0; 14 | while (i <= right) { 15 | if (nums[i] == 0) 16 | swap(nums[i++], nums[left++]); 17 | else if (nums[i] == 2) 18 | swap(nums[i], nums[right--]); 19 | else 20 | i++; 21 | } 22 | } 23 | }; 24 | 25 | 26 | int main() { 27 | Solution s; 28 | //int dat[] = {0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 1, 1, 2, 0}; 29 | int dat[] = {2}; 30 | vector vec(dat, dat + sizeof(dat) / sizeof(int)); 31 | s.sortColors(vec); 32 | for (int i = 0; i < vec.size(); i++) 33 | cout << vec[i] << " "; 34 | 35 | } -------------------------------------------------------------------------------- /c++/77_Combinations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | vector > combine(int n, int k) { 12 | vector res; 13 | vector > result; 14 | backtracking(1, k, n, res, result); 15 | return result; 16 | } 17 | void backtracking(int start, int k, int n, vector res, vector > &result) { 18 | if (res.size() == k) 19 | result.push_back(res); 20 | for (int i = start; i < n + 1; i++) { 21 | res.push_back(i); 22 | backtracking(i + 1, k, n, res, result); 23 | res.pop_back(); // extremly important 24 | } 25 | } 26 | }; 27 | 28 | 29 | int main() { 30 | Solution s; 31 | vector > result = s.combine(4, 2); 32 | for (int i = 0; i < result.size(); i++) { 33 | for (int j = 0; j < result[i].size(); j++) 34 | cout << result[i][j] << " "; 35 | cout << endl; 36 | } 37 | } -------------------------------------------------------------------------------- /c++/78_Subsets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | vector > subsets(vector& nums) { 12 | vector part; 13 | vector > res; 14 | res.push_back(part); 15 | dfs(0, nums, part, res); 16 | return res; 17 | } 18 | 19 | void dfs(int start, vector num, vector part, vector > &res) { 20 | if (num.size() == 0) 21 | return; 22 | for (int i = start; i < num.size(); i++) { 23 | part.push_back(num[i]); 24 | res.push_back(part); 25 | dfs(i + 1, num, part, res); 26 | part.pop_back(); 27 | } 28 | } 29 | }; 30 | 31 | 32 | int main() { 33 | Solution s; 34 | int dat[] = {1,2,3}; 35 | vector num(dat, dat + 3); 36 | vector > res = s.subsets(num); 37 | for (int i = 0; i < res.size(); i++) { 38 | for (int j = 0; j < res[i].size(); j++) 39 | cout << res[i][j] << " "; 40 | cout << endl; 41 | } 42 | } -------------------------------------------------------------------------------- /c++/80_Remove_Duplicates_from_Sorted_Array_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int removeDuplicates(vector& nums) { 12 | int n = nums.size(); 13 | if (n < 3) 14 | return n; 15 | int total = 2, i = 2; 16 | while (i < n) { 17 | if (nums[i] == nums[i - 2]) { 18 | n--; 19 | nums.erase(nums.begin() + i); 20 | continue; 21 | } 22 | total++; 23 | i++; 24 | } 25 | return total; 26 | } 27 | }; 28 | 29 | 30 | int main() { 31 | Solution s; 32 | } -------------------------------------------------------------------------------- /c++/81_Search_in_Rotated_Sorted_Array_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | bool search(vector& nums, int target) { 12 | int left = 0, right = nums.size() - 1; 13 | while (left <= right) { 14 | int mid = left + (right - left) / 2; 15 | if (nums[mid] == target) 16 | return true; 17 | else if (nums[mid] > nums[right]) { 18 | if (target < nums[mid] and target >= nums[left]) 19 | right = mid - 1; 20 | else 21 | left = mid + 1; 22 | } 23 | else if (nums[mid] < nums[right]) { 24 | if (target > nums[mid] and target <= nums[right]) 25 | left = mid + 1; 26 | else 27 | right = mid -1; 28 | } 29 | else 30 | right--; 31 | } 32 | return false; 33 | } 34 | }; -------------------------------------------------------------------------------- /c++/83_Remove_Duplicates_from_Sorted_List.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode(int x) : val(x), next(NULL) {} 14 | * }; 15 | */ 16 | 17 | 18 | class Solution { 19 | public: 20 | ListNode* deleteDuplicates(ListNode* head) { 21 | if (!head) 22 | return head; 23 | ListNode *p = head; 24 | while (p->next){ 25 | if (p->next->val == p->val) 26 | p->next = p->next->next; 27 | else 28 | p = p->next; 29 | } 30 | return head; 31 | 32 | 33 | } 34 | }; 35 | 36 | 37 | int main() { 38 | 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /c++/84_Largest_Rectangle_in_Histogram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int largestRectangleArea(vector& heights) { 12 | if (heights.size() == 0) return 0; 13 | stack stk; 14 | heights.push_back(-1); 15 | heights.insert(heights.begin(), -1); 16 | int maxS = 0; 17 | for (int i = 0; i < heights.size(); i++) { 18 | while (!stk.empty() and heights[i] <= heights[stk.top()]) { 19 | int minH = heights[stk.top()]; 20 | stk.pop(); 21 | if (!stk.empty()) maxS = max(maxS, (i - stk.top() - 1) * minH); 22 | } 23 | stk.push(i); 24 | } 25 | heights.pop_back(); 26 | heights.erase(heights.begin()); 27 | return maxS; 28 | } 29 | }; 30 | 31 | int main() { 32 | Solution s; 33 | } -------------------------------------------------------------------------------- /c++/89_Gray_Code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | vector grayCode(int n) { 12 | vector res; 13 | if (n < 0) 14 | return res; 15 | res.push_back(0); 16 | int shift = 1; 17 | for (int i = 0; i < n; i++) { 18 | for (int j = res.size() - 1; j >= 0; j--) 19 | res.push_back(res[j] + shift); 20 | shift <<= 1; 21 | } 22 | return res; 23 | } 24 | }; 25 | 26 | -------------------------------------------------------------------------------- /c++/90_Subsets_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | vector > subsetsWithDup(vector& nums) { 12 | vector > res; 13 | vector part; 14 | res.push_back(part); 15 | dfs(0, nums, part, res); 16 | return res; 17 | } 18 | 19 | void dfs(int start, vector nums, vector part, vector > &res) { 20 | if (nums.size() == start) 21 | return; 22 | int last = 0; 23 | for (int i = start; i < nums.size(); i++) { 24 | if (i != start and nums[i] == last) 25 | continue; 26 | part.push_back(nums[i]); 27 | res.push_back(part); 28 | dfs(start + 1, nums, part, res); 29 | part.pop_back(); 30 | last = nums[i]; 31 | } 32 | } 33 | }; 34 | 35 | 36 | int main() { 37 | Solution s; 38 | } -------------------------------------------------------------------------------- /c++/91_Decode_Ways.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int numDecodings(string s) { 12 | int n = s.size(); 13 | if (n == 0 or s[0] == '0') 14 | return 0; 15 | int dp[n + 1] = {0}; 16 | dp[0] = 1; 17 | dp[1] = 1; 18 | 19 | for (int i = 2; i <= n; i++) { 20 | int fake_int = 10 * (s[i - 2] - '0') + s[i - 1] - '0'; 21 | // last 2 digits makes an integer between (10, 26] / 20 22 | if (fake_int > 10 and fake_int <= 26 and fake_int != 20) 23 | dp[i] = dp[i - 1] + dp[i - 2]; 24 | else if (fake_int == 10 or fake_int == 20) // last 2 are 10 or 20 25 | dp[i] = dp[i - 2]; 26 | else if (s[i - 1] != '0') // ***** important condition 27 | dp[i] = dp[i - 1]; 28 | else 29 | return 0; 30 | } 31 | return dp[n]; 32 | } 33 | }; 34 | 35 | 36 | int main() { 37 | Solution s; 38 | cout << s.numDecodings("100") << endl; 39 | } -------------------------------------------------------------------------------- /c++/92_Reverse_Linked_List_II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * struct ListNode { 12 | * int val; 13 | * ListNode *next; 14 | * ListNode(int x) : val(x), next(NULL) {} 15 | * }; 16 | */ 17 | class Solution { 18 | public: 19 | ListNode* reverseBetween(ListNode* head, int m, int n) { 20 | if (m == n) 21 | return head; 22 | ListNode *p = new ListNode(0); 23 | p->next = head; 24 | head = p; 25 | ListNode *left = p, *right = p; 26 | for (int i = 0; i < m; i++) { 27 | left = left->next; 28 | if (i != m - 1) 29 | p = p->next; 30 | } 31 | for (int i = 0; i < n; i++) 32 | right = right->next; 33 | p->next = right; 34 | right = right->next; 35 | 36 | for (int i = n - m; i > 0; i--) { 37 | ListNode *tmp = left; 38 | for (int j = i - 1; j > 0; j--) 39 | tmp = tmp->next; 40 | tmp->next->next = tmp; 41 | } 42 | left->next = right; 43 | return head->next; 44 | } 45 | }; 46 | 47 | 48 | int main() { 49 | Solution s; 50 | } -------------------------------------------------------------------------------- /c++/96_Unique_Binary_Search_Trees.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int numTrees(int n) { 12 | int dp[n + 1] = {0}; 13 | dp[0] = 1; 14 | for (int i = 1; i <= n; i++) 15 | for (int j = 0; j < i; j++) 16 | dp[i] += dp[j] * dp[i - 1 - j]; 17 | return dp[n]; 18 | } 19 | }; 20 | 21 | 22 | int main() { 23 | Solution s; 24 | } -------------------------------------------------------------------------------- /c++/97_Interleaving_String.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | bool isInterleave(string s1, string s2, string s3) { 12 | int m = s1.size(), n = s2.size(); 13 | if (m + n != s3.size()) 14 | return false; 15 | int dp[m + 1][n + 1] = {0}; 16 | dp[0][0] = true; 17 | for (int i = 0; i < m; i++) 18 | if (s1[i] == s3[i] and dp[i][0]) 19 | dp[i + 1][0] = true; 20 | for (int i = 0; i < n; i++) 21 | if (s2[i] == s3[i] and dp[0][i]) 22 | dp[0][i + 1] = true; 23 | for (int i = 0; i < m; i++) { 24 | for (int j = 0; j < n; j++) { 25 | if (s3[i + j + 1] == s1[i] and dp[i][j + 1]) 26 | dp[i + 1][j + 1] = dp[i][j + 1]; 27 | else if (s3[i + j + 1] == s2[j] and dp[i + 1][j]) 28 | dp[i + 1][j + 1] = dp[i + 1][j]; 29 | } 30 | } 31 | return dp[m][n]; 32 | 33 | } 34 | }; -------------------------------------------------------------------------------- /c++/c++11.sublime.settting: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "shell_cmd": "g++ -std=c++11 \"${file}\" -o \"${file_path}/${file_base_name}\"", 4 | "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", 5 | "working_dir": "${file_path}", 6 | "selector": "source.c, source.c++", 7 | 8 | "variants": 9 | [ 10 | { 11 | "name": "Run", 12 | "shell_cmd": "g++ -std=c++11 \"${file}\" -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\"" 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /python/01_Two_Sum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | ''' 6 | Given nums = [2, 7, 11, 15], target = 9, 7 | 8 | Because nums[0] + nums[1] = 2 + 7 = 9, 9 | return [0, 1]. 10 | ''' 11 | 12 | class Solution(object): 13 | def twoSum(self, nums, target): 14 | d = {} 15 | # set key as default if the key is not in dict 16 | for num, dat in enumerate(nums): 17 | # set key to be value, value to be the loc 18 | d.setdefault(dat,[]).append(num) 19 | for num in d: 20 | if target - num in nums and target - num == num: 21 | # in this case, d[num] must be a tuple 22 | return d[num] 23 | elif target - num in nums and target - num != num: 24 | return sorted([d[num][0], d[target - num][0]]) 25 | 26 | 27 | def main(): 28 | s = Solution() 29 | print s.twoSum([2, 7, 2, 11, 2, 15], 4) 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /python/02_Add_Two_Numbers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | ''' 6 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 7 | Output: 7 -> 0 -> 8 8 | ''' 9 | 10 | class Solution(object): 11 | # Linked list 12 | def addTwoNumbers(self, l1, l2): 13 | head = ListNode(0) 14 | l = head 15 | carry = 0 16 | while carry or l1 or l2: 17 | carry, sum = 0, carry 18 | if l1: 19 | sum += l1.val 20 | l1 = l1.next 21 | if l2: 22 | sum += l2.val 23 | l2 = l2.next 24 | if sum > 9: 25 | sum -= 10 26 | carry = 1 27 | l.next = ListNode(sum) 28 | l = l.next 29 | return head.next 30 | 31 | 32 | def main(): 33 | s = Solution() 34 | 35 | if __name__ == "__main__": 36 | main() 37 | -------------------------------------------------------------------------------- /python/03_Longest_Substring_Without_Repeating_Characters.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given "abcabcbb", the answer is "abc", which the length is 3. 3 | 4 | Given "bbbbb", the answer is "b", with the length of 1. 5 | 6 | Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 7 | ''' 8 | 9 | class Solution(object): 10 | # get longest substring 11 | def lengthOfLongestSubstring(self, s): 12 | last = -1 13 | maximum = 0 14 | n = len(s) 15 | sets = {} 16 | for i in range(n): 17 | # last < sets[] is to get rid of cases as "abba" 18 | if s[i] in sets and last < sets[s[i]]: 19 | last = sets[s[i]] 20 | sets[s[i]] = i 21 | maximum = max(i - last, maximum) 22 | return maximum 23 | -------------------------------------------------------------------------------- /python/04_Median_of_Two_Sorted_Arrays.py: -------------------------------------------------------------------------------- 1 | ''' 2 | nums1 = [1, 3] 3 | nums2 = [2] 4 | 5 | The median is 2.0 6 | 7 | nums1 = [1, 2] 8 | nums2 = [3, 4] 9 | 10 | The median is (2 + 3)/2 = 2.5 11 | ''' 12 | class Solution(object): 13 | # hard 14 | def findMedianSortedArrays(self, num1, num2): 15 | m = len(num1) 16 | n = len(num2) 17 | mid = (m + n) / 2 18 | if (m + n) % 2 == 1: 19 | return self.findK(num1, m, num2, n, mid + 1) 20 | else: 21 | mid1 = self.findK(num1, m, num2, n, mid) 22 | mid2 = self.findK(num1, m, num2, n, mid + 1) 23 | print mid1, mid2 24 | return float(mid1 + mid2) / 2 25 | 26 | def findK(self, num1, m, num2, n, k): 27 | if m == 0: 28 | return num2[k - 1] 29 | if n == 0: 30 | return num1[k - 1] 31 | i = m / 2 32 | j = n / 2 33 | print m, n, i, j, k 34 | if num1[i] <= num2[j]: 35 | if k > i + j + 1: 36 | return self.findK(num1[i + 1:], m - i - 1, num2, n, k - i - 1) 37 | else: 38 | return self.findK(num1, m, num2, j, k) 39 | else: 40 | return self.findK(num2, n, num1, m, k) 41 | -------------------------------------------------------------------------------- /python/05_Longest_Palindromic_Substring.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # time complexity 3 | def longestPalindrome(self, s): 4 | substring = '' 5 | for i in xrange(len(s)): 6 | subS = self.ifPalin(s, i, i) 7 | if len(subS) > len(substring): 8 | substring = subS 9 | # for even case 10 | subS = self.ifPalin(s, i, i + 1) 11 | if len(subS) > len(substring): 12 | substring = subS 13 | return substring 14 | 15 | def ifPalin(self, s, start, end): 16 | while start >= 0 and end < len(s) and s[start] == s[end]: 17 | start -= 1 18 | end += 1 19 | 20 | return s[start + 1:end] 21 | -------------------------------------------------------------------------------- /python/06_ZigZag_Conversion.py: -------------------------------------------------------------------------------- 1 | ''' 2 | P A H N 3 | A P L S I I G 4 | Y I R 5 | And then read line by line: "PAHNAPLSIIGYIR" 6 | ''' 7 | 8 | class Solution: 9 | # python may run out of time 10 | def convert(self, s, numRows): 11 | sub = "" 12 | if numRows < 2 or len(s) <= numRows: 13 | return s 14 | for i in xrange(numRows): 15 | tmp = 0 16 | while tmp + i < len(s): 17 | if i > 0 and i < numRows - 1 and tmp > i: 18 | sub += s[tmp - i] 19 | sub += s[tmp + i] 20 | tmp += 2 * (numRows - 1) 21 | 22 | if tmp + i >= len(s) and tmp - i < len(s) and i < numRows - 1: 23 | sub += s[tmp - i] 24 | return sub 25 | -------------------------------------------------------------------------------- /python/07_Reverse_Integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | import math 5 | 6 | class Solution: 7 | def reverse(self, x): 8 | sign = 1 if x > 0 else -1 9 | output = 0 10 | x = abs(x) 11 | while x: 12 | if output > 214748364: 13 | return 0; 14 | output = 10 * output + x % 10 15 | x /= 10 16 | return sign * output 17 | 18 | def main(): 19 | s = Solution() 20 | print s.reverse(1) 21 | 22 | if __name__ == "__main__": 23 | main() 24 | -------------------------------------------------------------------------------- /python/08_String_to_Integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | import re 5 | 6 | class Solution: 7 | def myAtoi(self, str): 8 | INT_MAX = 2 ** 31 - 1 9 | INT_MIN = -2 ** 31 10 | str = str.strip().split(" ")[0] 11 | if len(str) == 0: 12 | return 0 13 | # tag is used for counting the start point 14 | tag = 0 15 | n = len(str) 16 | num = 0 17 | if str[0] == '-': 18 | tag = -1 19 | elif str[0] == '+': 20 | tag = 1 21 | for i in xrange(abs(tag), n): 22 | if str[i].isdigit(): 23 | num = 10 * num + int(str[i]) 24 | else: 25 | break 26 | if tag == -1: 27 | return max(tag * num, INT_MIN) 28 | else: 29 | return min(num, INT_MAX) 30 | 31 | 32 | 33 | def main(): 34 | s = Solution() 35 | print s.myAtoi(" -0012a41 ") 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /python/09_Palindrome_Number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | from math import log 5 | 6 | class Solution: 7 | def isPalindrome(self, x): 8 | if x < 0: 9 | return False 10 | exp = 1 11 | while x / 10 ** exp > 0: 12 | exp += 1 13 | while x: 14 | left = x / 10 ** (exp - 1) 15 | right = x % 10 16 | if left != right: 17 | return False 18 | x = x % (10 ** (exp - 1)) / 10 19 | exp -= 2 20 | return True 21 | 22 | 23 | def main(): 24 | s = Solution() 25 | print s.isPalindrome(1478118741) 26 | if __name__ == "__main__": 27 | main() 28 | -------------------------------------------------------------------------------- /python/10_Regular_Expression_Matching.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution: 6 | # @return a boolean 7 | def isMatch(self, s, p): 8 | m = len(s) 9 | n = len(p) 10 | dp = [[False for i in range(n + 1)] for j in range(m + 1)] 11 | dp[0][0] = True 12 | 13 | for i in range(0, m + 1): 14 | for j in range(1, n + 1): 15 | if i > 0 and p[j - 1] == '.': 16 | dp[i][j] = dp[i - 1][j - 1] 17 | elif p[j - 1] == '*': 18 | if i == 0 and j > 1: 19 | dp[i][j] = dp[i][j - 2] 20 | if i != 0: 21 | dp[i][j] = dp[i][j - 1] or dp[i][j - 2] or (dp[i - 1][j] and (s[i - 1]==p[j - 2] or p[j - 2]=='.')) 22 | elif i > 0: 23 | dp[i][j]=dp[i-1][j-1] and s[i-1]==p[j-1] 24 | return dp[m][n] 25 | 26 | 27 | def main(): 28 | s = Solution() 29 | print s.isMatch("abc","bc") 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /python/11_Container_With_Most_Water.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution: 6 | def maxArea(self, height): 7 | ''' 8 | height: List[int] 9 | rtype: int 10 | ''' 11 | out = 0 12 | left = 0 13 | 14 | right = len(height) - 1 15 | while left < right: 16 | water = min(height[left], height[right]) * (right - left) 17 | print left, right, water 18 | if out < water: 19 | out = water 20 | if height[left] > height[right]: 21 | right -= 1 22 | else: 23 | left += 1 24 | 25 | return out 26 | 27 | 28 | 29 | 30 | def main(): 31 | s = Solution() 32 | print s.maxArea([1,2,4,3]) 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /python/12_Integer_to_Roman.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution: 6 | def intToRoman(self, num): 7 | values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] 8 | numerals = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] 9 | list = '' 10 | for i in range(len(values)): 11 | while num >= values[i]: 12 | num -= values[i] 13 | list += numerals[i] 14 | return list 15 | 16 | def main(): 17 | s = Solution() 18 | print s.intToRoman(50) 19 | 20 | if __name__ == "__main__": 21 | main() 22 | -------------------------------------------------------------------------------- /python/13_Roman_to_Integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import string 4 | import os 5 | 6 | class Solution: 7 | def romanToInt(self, s): 8 | values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] 9 | numerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] 10 | out = 0 11 | for i in range(13): 12 | while s.startswith(numerals[i]): 13 | # use replace for a string and pop or remove for a list 14 | s = string.replace(s, numerals[i], '', 1) 15 | out += values[i] 16 | return out 17 | 18 | 19 | 20 | def main(): 21 | s = Solution() 22 | s.romanToInt("DCXXI") 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /python/14_Longest_Common_Prefix.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def longestCommonPrefix(self, strs): 7 | lcp = "" 8 | if len(strs) < 1: 9 | return lcp 10 | for i in range(len(strs[0])): 11 | for j in range(1, len(strs)): 12 | if i >= len(strs[j]) or strs[0][i] != strs[j][i]: 13 | return lcp 14 | lcp += strs[0][i] 15 | return lcp 16 | 17 | 18 | def main(): 19 | s = Solution() 20 | strs = ["abc", "abd"] 21 | print s.longestCommonPrefix(strs) 22 | 23 | if __name__ == "__main__": 24 | main() 25 | -------------------------------------------------------------------------------- /python/16_3Sum_Closest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | import math 5 | 6 | ''' 7 | For example, given array S = {-1 2 1 -4}, and target = 1. 8 | 9 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 10 | ''' 11 | 12 | class Solution: 13 | def threeSumClosest(self, nums, target): 14 | nums.sort() 15 | out = 0 16 | MIN = 10 ** 10 17 | for i in range(len(nums) - 2): 18 | left = i + 1 19 | right = len(nums) - 1 20 | while left < right: 21 | total = nums[i] + nums[left] + nums[right] 22 | if total == target: 23 | return target 24 | elif total < target: 25 | left += 1 26 | else: 27 | right -= 1 28 | diff = abs(total - target) 29 | if diff < MIN: 30 | MIN = diff 31 | out = total 32 | return out 33 | 34 | def main(): 35 | s = Solution() 36 | print s.threeSumClosest([-1, 2, 1, -4], 1) 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /python/17_Letter_Combinations_of_a_Phone_Number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | ''' 6 | Input:Digit string "23" 7 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 8 | ''' 9 | 10 | class Solution(object): 11 | def letterCombinations(self, digits): 12 | Lists = {'2':['a','b','c'], 13 | '3':['d','e','f'], 14 | '4':['g','h','i'], 15 | '5':['j','k','l'], 16 | '6':['m','n','o'], 17 | '7':['p','q','r','s'], 18 | '8':['t','u','v'], 19 | '9':['w','x','y','z'] 20 | } 21 | res = [""] 22 | for num in range(len(digits)): 23 | tmp = [] 24 | for i in res: 25 | for j in Lists[digits[num]]: 26 | tmp.append(i + j) 27 | res = tmp 28 | ''' 29 | # Never use such loops, otherwise there will be infinite loops 30 | for i in res: 31 | for j in Lists[digits[num]]: 32 | res.append(i + j) 33 | ''' 34 | if digits == "": 35 | res.remove("") 36 | return res 37 | 38 | 39 | def main(): 40 | s = Solution() 41 | print s.letterCombinations("") 42 | 43 | if __name__ == "__main__": 44 | main() 45 | -------------------------------------------------------------------------------- /python/18_4Sum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | ''' 6 | For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. 7 | 8 | A solution set is: 9 | [ 10 | [-1, 0, 0, 1], 11 | [-2, -1, 1, 2], 12 | [-2, 0, 0, 2] 13 | ] 14 | ''' 15 | 16 | class Solution(object): 17 | def fourSum(self, nums, target): 18 | """ 19 | :type nums: List[int] 20 | :type target: int 21 | :rtype: List[List[int]] 22 | """ 23 | # sacrifice space to exchange for efficiency 24 | nums.sort() 25 | res, length, valuePair = [], len(nums), {} 26 | if length < 4: 27 | return null 28 | 29 | for i in range(length - 1): 30 | for j in range(i + 1, length): 31 | valuePair.setdefault(nums[i] + nums[j], []).append((i, j)) 32 | 33 | for i in range(length - 2): 34 | for j in range(i + 1, length): 35 | T = target - nums[i] - nums[j] 36 | if T in valuePair: 37 | index = valuePair[T] 38 | for k in index: 39 | if k[0] > j: 40 | res.append((nums[i], nums[j], nums[k[0]], nums[k[1]])) 41 | return list(set(res)) 42 | 43 | 44 | 45 | 46 | def main(): 47 | s = Solution() 48 | print s.fourSum([1, 0, -1, 0, -2, 2], 0) 49 | 50 | if __name__ == "__main__": 51 | main() 52 | -------------------------------------------------------------------------------- /python/19_Remove_Nth_Node_From_End_of_List.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | from llist import dllist, dllistnode 5 | # https://pythonhosted.org/llist/ 6 | 7 | 8 | class Solution(object): 9 | def removeNthFromEnd(self, head, n): 10 | """ 11 | :type head: ListNode 12 | :type n: int 13 | :rtype: ListNode 14 | """ 15 | first, second = head, head 16 | i = 0 17 | while i < n + 1 and first: 18 | first = first.next 19 | i = i + 1 20 | 21 | if i == n + 1: 22 | while first: 23 | first = first.next 24 | second = second.next 25 | second.next = second.next.next 26 | else: 27 | head = head.next 28 | return head -------------------------------------------------------------------------------- /python/20_Valid_Parentheses.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def isValid(self, s): 7 | """ 8 | :type s: str 9 | :rtype: bool 10 | """ 11 | stk = [] 12 | for i in range(len(s)): 13 | if s[i] == '(' or s[i] == '[' or s[i] == '{': 14 | stk.append(s[i]) 15 | else: 16 | if stk == [] or self.unmatch(stk.pop(), s[i]): 17 | return False 18 | return stk == [] 19 | 20 | def unmatch(self, a, b): 21 | if a == '(': 22 | return b != ')' 23 | elif a == '[': 24 | return b != ']' 25 | elif a == '{': 26 | return b != '}' 27 | else: 28 | return False 29 | 30 | 31 | 32 | def main(): 33 | s = Solution() 34 | print s.isValid("[") 35 | 36 | if __name__ == "__main__": 37 | main() 38 | -------------------------------------------------------------------------------- /python/21_Merge_Two_Sorted_Lists.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | # Definition for singly-linked list. 6 | # class ListNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.next = None 10 | 11 | class Solution(object): 12 | def mergeTwoLists(self, l1, l2): 13 | """ 14 | :type l1: ListNode 15 | :type l2: ListNode 16 | :rtype: ListNode 17 | """ 18 | head = ListNode(0) 19 | tmp = head 20 | while l1 and l2: 21 | if l1.val < l2.val: 22 | tmp.next = l1 23 | l1 = l1.next 24 | else: 25 | tmp.next = l2 26 | l2 = l2.next 27 | tmp = tmp.next 28 | tmp.next = l1 if l1 else l2 29 | return head.next 30 | 31 | def main(): 32 | s = Solution() 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /python/23_Merge_k_Sorted_Lists.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def mergeKLists(self, lists): 7 | """ 8 | :type lists: List[ListNode] 9 | :rtype: ListNode 10 | """ 11 | if len(lists) == 0: 12 | return None 13 | right = len(lists) - 1 14 | while right > 0: 15 | left = 0 16 | while left < right: 17 | lists[left] = self.two_merge(lists[left], lists[right]) 18 | left += 1 19 | right -= 1 20 | return lists[0] 21 | def two_merge(self, l1, l2): 22 | head = ListNode(0) 23 | out = head 24 | while l1 and l2: 25 | if l1.val < l2.val: 26 | out.next = l1 27 | l1 = l1.next 28 | else: 29 | out.next = l2 30 | l2 = l2.next 31 | out = out.next 32 | out.next = l1 if l1 else l2 33 | return head.next 34 | 35 | 36 | def main(): 37 | s = Solution() 38 | 39 | if __name__ == "__main__": 40 | main() 41 | -------------------------------------------------------------------------------- /python/24_Swap_Nodes_in_Pairs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | # Definition for singly-linked list. 6 | # class ListNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.next = None 10 | 11 | class Solution(object): 12 | def swapPairs(self, head): 13 | """ 14 | :type head: ListNode 15 | :rtype: ListNode 16 | """ 17 | if not head or not head.next: 18 | return head 19 | p = ListNode(0) 20 | p.next = head 21 | q = p 22 | while q.next and q.next.next: 23 | tmp = q.next.next 24 | # the following 2 lines cannot be interchanged 25 | # otherwise q.next.next won't point to the target since tmp.next has changed 26 | q.next.next = tmp.next 27 | tmp.next = q.next 28 | q.next = tmp 29 | q = q.next.next 30 | return p.next 31 | 32 | 33 | 34 | 35 | def main(): 36 | s = Solution() 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /python/25_Reverse_Nodes_in_k-Group.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution: 6 | def reverse(self, start, end): 7 | newhead = ListNode(0) 8 | newhead.next = start 9 | while newhead.next != end: 10 | tmp = start.next 11 | start.next = tmp.next 12 | tmp.next = newhead.next 13 | newhead.next = tmp 14 | return [end, start] 15 | def reverseKGroup(self, head, k): 16 | if head == None: 17 | return None 18 | nhead = ListNode(0) 19 | nhead.next = head 20 | start = nhead 21 | while start.next: 22 | end = start 23 | for i in range(k-1): 24 | end = end.next 25 | if end.next == None: 26 | return nhead.next 27 | start.next, start =self.reverse(start.next, end.next) 28 | return nhead.next 29 | 30 | def main(): 31 | s = Solution() 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /python/26_Remove_Duplicates_from_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def removeDuplicates(self, nums): 7 | n = len(nums) 8 | if n <= 1: 9 | return nums 10 | i, j = 0, 1 11 | while i < n - j: 12 | if nums[i] == nums[i + 1]: 13 | nums.remove(nums[i]) 14 | j += 1 15 | else: 16 | i += 1 17 | return nums 18 | 19 | 20 | 21 | def main(): 22 | s = Solution() 23 | print s.removeDuplicates([0, 1, 1, 2, 2, 2, 3]) 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /python/27_Remove_Element.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def removeElement(self, nums, val): 7 | n = len(nums); 8 | i, j = 0, 0 9 | while i < n - j: 10 | if nums[i] == val: 11 | nums.remove(nums[i]) 12 | j += 1 13 | else: 14 | i += 1 15 | return len(nums) 16 | 17 | 18 | def main(): 19 | s = Solution() 20 | print s.removeElement([1, 2, 2, 3], 2) 21 | 22 | if __name__ == "__main__": 23 | main() 24 | -------------------------------------------------------------------------------- /python/28_Implement.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def strStr(self, haystack, needle): 7 | n, m = len(haystack), len(needle) 8 | if m == 0: 9 | return 0 10 | if n == 0: 11 | return -1 12 | for i in range(n - m + 1): 13 | j = 0 14 | while j < m: 15 | if haystack[i + j] == needle[j]: 16 | j += 1 17 | else: 18 | break 19 | if j == m: 20 | return i 21 | return -1 22 | 23 | 24 | 25 | def main(): 26 | s = Solution() 27 | print s.strStr("abcdefghqwertyuiop", "defg") 28 | print s.strStr("a", "a") 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /python/29_Divide_Two_Integers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def divide(self, dividend, divisor): 7 | sign = 1 8 | if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0): 9 | sign = -1 10 | dd, ds = abs(dividend), abs(divisor) 11 | if dd < ds: 12 | return 0 13 | if dividend == -2 ** 31 and divisor == -1: 14 | return 2 ** 31 - 1 15 | res = 0 16 | while ds <= dd: 17 | bs_ds = ds # bit shift operator 18 | part = 1 19 | while not (bs_ds <= dd and bs_ds + bs_ds > dd): 20 | bs_ds += bs_ds 21 | part += part 22 | dd -= bs_ds 23 | res += part 24 | return res * sign 25 | 26 | def main(): 27 | s = Solution() 28 | print s.divide(16, 3) 29 | print s.divide(-1, 1) 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /python/31_Next_Permutation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | 6 | #https://www.nayuki.io/page/next-lexicographical-permutation-algorithm 7 | class Solution(object): 8 | def nextPermutation(self, nums): 9 | n = len(nums) 10 | if n < 2: 11 | return 12 | i = n - 2 13 | while i >= 0 and nums[i] >= nums[i + 1]: 14 | i -= 1 15 | if i < 0: 16 | nums.reverse() 17 | return 18 | j = i + 1 19 | while j < n and nums[j] > nums[i]: 20 | j += 1 21 | j -= 1 22 | nums[i], nums[j] = nums[j], nums[i] 23 | nums[i + 1: n] = nums[i + 1: n][::-1] 24 | return 25 | 26 | 27 | def main(): 28 | s = Solution() 29 | nums = [0, 1, 2, 5, 3, 3, 0] 30 | #nums = [1, 2] 31 | s.nextPermutation(nums) 32 | print nums 33 | 34 | 35 | if __name__ == "__main__": 36 | main() 37 | -------------------------------------------------------------------------------- /python/32_Longest_Valid_Parentheses.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def longestValidParentheses(self, s): 7 | n, maxLen = len(s), 0 8 | dp = [0 for i in range(n)] 9 | if n < 2: 10 | return 0 11 | 12 | for i in range(1, n): 13 | j = i - 2 - dp[i - 1] 14 | if j < -1 or s[j + 1] == ')' or s[i] == '(': 15 | dp[i] = 0 16 | else: 17 | dp[i] = dp[j] + 2 + dp[i - 1] 18 | maxLen = max(maxLen, dp[i]) 19 | return maxLen 20 | 21 | 22 | 23 | 24 | def main(): 25 | s = Solution() 26 | print s.longestValidParentheses(")()())") 27 | 28 | if __name__ == "__main__": 29 | main() 30 | -------------------------------------------------------------------------------- /python/33_Search_in_Rotated_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | 6 | class Solution: 7 | def search(self, nums, target): 8 | minimum = self.findMin(nums, 0, nums[0]) 9 | nums = nums[minimum:] + nums[:minimum] 10 | loc = self.binSearch(nums, target, 0) 11 | if loc == -1: 12 | return loc 13 | if loc < len(nums) - minimum: 14 | return minimum + loc 15 | else: 16 | return loc - len(nums) + minimum 17 | 18 | def findMin(self, nums, loc, first): 19 | n = len(nums) 20 | if n == 1: 21 | return loc 22 | if n == 2: 23 | if nums[0] > nums[1]: 24 | return loc + 1 25 | else: 26 | return 0 27 | 28 | if nums[n / 2] > first: 29 | loc = self.findMin(nums[n/2:], loc + n/2, first) 30 | else: 31 | loc = self.findMin(nums[:(n/2 + 1)], loc, first) 32 | return loc 33 | 34 | def binSearch(self, nums, target, loc): 35 | n = len(nums) 36 | print nums 37 | if n == 1: 38 | return loc if nums[0] == target else - 1 39 | if nums[n / 2] > target: 40 | loc = self.binSearch(nums[:n / 2], target, loc) 41 | else: 42 | loc = self.binSearch(nums[n / 2:], target, loc + n / 2) 43 | return loc 44 | 45 | 46 | def main(): 47 | s = Solution() 48 | print s.search([4,5,6,1,2,3], 4) 49 | 50 | 51 | if __name__ == "__main__": 52 | main() 53 | -------------------------------------------------------------------------------- /python/35_Search_Insert_Position.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def searchInsert(self, nums, target): 7 | n = len(nums) 8 | loc = self.binSearch(nums, target, 0) 9 | #print "?" , loc 10 | if nums[loc] == target: 11 | return loc 12 | elif nums[loc] < target: 13 | return loc + 1 14 | return 0 15 | # search the minimum location of the array 16 | def binSearch(self, nums, target, loc): 17 | n = len(nums) 18 | if n == 1: 19 | return loc 20 | mid = n / 2 21 | if nums[mid] <= target: 22 | loc = self.binSearch(nums[mid: n], target, loc + mid) 23 | else: 24 | loc = self.binSearch(nums[0: mid], target, loc) 25 | return loc 26 | 27 | 28 | def main(): 29 | s = Solution() 30 | nums = [5, 7, 8, 10] 31 | target = 9 32 | nums = [1] 33 | target = 0 34 | print s.binSearch(nums, target, 0) 35 | print s.searchInsert(nums, target) 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /python/36_Valid_Sudoku.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def isValidSudoku(self, board): 7 | """ 8 | :type board: List[List[str]] 9 | :rtype: bool 10 | """ 11 | row, col, grid = {}, {}, {} 12 | for i in range(9): 13 | row[i], col[i], grid[i] = [], [], [] 14 | for i in range(9): 15 | for j in range(9): 16 | if board[i][j] == '.': 17 | continue 18 | num = i / 3 * 3 + j / 3 19 | if board[i][j] in col[j] or board[i][j] in row[i] or board[i][j] in grid[num]: 20 | return False 21 | 22 | row[i].append(board[i][j]) 23 | col[j].append(board[i][j]) 24 | grid[num].append(board[i][j]) 25 | return True 26 | 27 | 28 | def main(): 29 | s = Solution() 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /python/38_Count_and_Say.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | 6 | class Solution(object): 7 | def count(self, n): 8 | last = '*' 9 | count = 0 10 | res = "" 11 | for i in str(n): # don't use enumerate to skip 1st loop, insufficient 12 | if last != '*' and last != i: 13 | res += str(count) + last 14 | count = 0 15 | count += 1 16 | last = i 17 | res += str(count) + last 18 | return res 19 | def countAndSay(self, n): 20 | s='1' 21 | for i in range(2,n+1): 22 | s=self.count(s) 23 | return s 24 | 25 | 26 | def main(): 27 | s = Solution() 28 | print s.countAndSay(5) 29 | 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /python/39_Combination_Sum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | 6 | ''' 7 | [2, 3, 6, 7] and target 7, -> [ [7], [2, 2, 3] ] 8 | ''' 9 | 10 | class Solution(object): 11 | def combinationSum(self, nums, target): 12 | nums = sorted(nums) 13 | res, part = [], [] 14 | return self.dfs(nums, target, part, res) 15 | 16 | def dfs(self, nums, target, part, res): 17 | if target == 0: 18 | res.append(part) 19 | n = len(nums) 20 | for i in range(n): 21 | if nums[i] > target: 22 | break 23 | self.dfs(nums[i:n], target - nums[i], part + [nums[i]], res) 24 | return res 25 | 26 | def main(): 27 | s = Solution() 28 | nums = [2, 3, 6, 7] 29 | target = 7 30 | print s.combinationSum(nums, target) 31 | 32 | if __name__ == "__main__": 33 | main() 34 | -------------------------------------------------------------------------------- /python/40_Combination_Sum_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def combinationSum2(self, num, target): 7 | num = sorted(num) 8 | part, res = [], [] 9 | res = self.dfs(num, target, part, res) 10 | # delete duplicates 11 | last, i = "None", 0 12 | res = sorted(res) 13 | while i < len(res): 14 | if res[i] == last: 15 | res.remove(res[i]) 16 | else: 17 | last = res[i] 18 | i += 1 19 | return res 20 | 21 | def dfs(self, num, target, part, res): 22 | if target == 0: 23 | res.append(part) 24 | n = len(num) 25 | for i in range(n): 26 | if num[i] > target: 27 | break 28 | self.dfs(num[(i + 1):n], target - num[i], part + [num[i]], res) 29 | return res 30 | 31 | def main(): 32 | s = Solution() 33 | vec = [1] 34 | target = 1 35 | print s.combinationSum2(vec, target) 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /python/41_First_Missing_Positive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def firstMissingPositive(self, A): 7 | i, n = 0, len(A) 8 | if n == 0: 9 | return 1 10 | while i < n: 11 | if A[i] != i + 1 and A[i] > 0 and A[i] < n and A[A[i] - 1] != A[i]: 12 | A[A[i] - 1], A[i] = A[i], A[A[i] - 1] 13 | else: 14 | i += 1 15 | for i in range(n): 16 | if A[i] != i + 1: 17 | return i + 1 18 | return n + 1 19 | 20 | 21 | def main(): 22 | s = Solution() 23 | print s.firstMissingPositive([3,4,-1,1]) 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /python/42_Trapping_Rain_Water.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def trap(self, height): 7 | n, vol = len(height), 0 8 | leftMax, rightMax = [0] * n, [0] * n 9 | for i in range(1, n): 10 | leftMax[i] = max(leftMax[i - 1], height[i - 1]) 11 | 12 | for i in range(n - 2, 0, -1): 13 | rightMax[i] = max(rightMax[i + 1], height[i + 1]) 14 | boundary = min(leftMax[i], rightMax[i]) 15 | if boundary > height[i]: 16 | vol += boundary - height[i] 17 | return vol 18 | 19 | 20 | 21 | def main(): 22 | s = Solution() 23 | print s.trap([0,1,0,2,1,0,1,3,2,1,2,1]) 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /python/45_Jump_Game_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def jump(self, nums): 7 | n, k = len(nums), 0 8 | jMax = 0; i = 0; lastMax = 0; tag = 0 9 | while jMax < n - 1: 10 | #print i, jMax 11 | while i <= lastMax: 12 | jMax = max(jMax, i + nums[i]) 13 | if jMax < i + 1: # it can't reach the next point, stop 14 | tag = 1 15 | break 16 | i += 1 17 | k += 1 18 | lastMax = jMax 19 | if tag: 20 | break 21 | return k 22 | 23 | 24 | def main(): 25 | s = Solution() 26 | print s.jump([7,0,9,6,9,6,1,7,9,0,1,2,9,0,3]) 27 | print s.jump([2, 1]) 28 | print s.jump([0]) 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /python/46_Permutations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution: 6 | def permute(self, num): 7 | n, res = len(num), [] 8 | if n <= 1: 9 | return [num] 10 | for i in range(n): 11 | for j in self.permute(num[:i] + num[(i + 1):]): 12 | res.append([num[i]] + j) 13 | return res 14 | 15 | 16 | 17 | def main(): 18 | s = Solution() 19 | a = [1, 2, 3] 20 | print s.permute(a) 21 | 22 | if __name__ == "__main__": 23 | main() 24 | -------------------------------------------------------------------------------- /python/47_Permutations_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def permuteUnique(self, nums): 7 | n, res = len(nums), [] 8 | if n <= 1: 9 | return [nums] 10 | 11 | nums, last = sorted(nums), "." 12 | for i in range(n): 13 | if last == nums[i]: 14 | continue 15 | for arr in self.permuteUnique(nums[:i] + nums[i + 1:]): 16 | res.append(arr + [nums[i]]) 17 | last = nums[i] 18 | return res 19 | 20 | 21 | 22 | 23 | 24 | def main(): 25 | s = Solution() 26 | print s.permuteUnique([1, 1, 2]) 27 | 28 | if __name__ == "__main__": 29 | main() 30 | -------------------------------------------------------------------------------- /python/48_Rotate_Image.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def rotate(self, matrix): 7 | for i in range(len(matrix)): 8 | for j in range(i + 1, len(matrix[i])): 9 | matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] 10 | 11 | for i in range(len(matrix)): 12 | matrix[i].reverse() 13 | 14 | def main(): 15 | s = Solution() 16 | mat = [[1, 2], [3, 4]] 17 | s.rotate(mat) 18 | print mat 19 | 20 | if __name__ == "__main__": 21 | main() 22 | -------------------------------------------------------------------------------- /python/50_Pow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def myPow(self, x, n): 7 | if n == 0: 8 | return 1 9 | if n < 0: 10 | return 1 / self.myPow(x, -n) 11 | if n == 1: 12 | return x 13 | out = self.myPow(x, n / 2) 14 | out *= out 15 | if n % 2 == 1: 16 | out *= x 17 | return out 18 | 19 | 20 | def main(): 21 | s = Solution() 22 | print s.myPow(34.00515, -3) 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /python/51_N-Queens.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | class Solution(object): 5 | def solveNQueens(self, n): 6 | def isValid(irow, icol, cols): 7 | for row, col in enumerate(cols): 8 | # diff cols and diags... 9 | if icol == col or abs(irow - row) == abs(icol - col): 10 | return False 11 | #if icol == col or abs(irow - icol) == abs(row - col): # [3,2] and [0, 1] 12 | return True 13 | def dfs(irow, cols, sol): 14 | if irow == n: 15 | allSol.append(sol) 16 | return 17 | for icol in range(n): 18 | if isValid(irow, icol, cols): 19 | row = ['.'] * n 20 | row[icol] = 'Q' 21 | #sol.append("".join(row)) # important, this way leads to the change of final solution 22 | dfs(irow + 1, cols + [icol], sol + ["".join(row)]) 23 | #sol.pop() 24 | 25 | # save coordinate of the columns 26 | allSol = [] 27 | dfs(0, [], []) 28 | return allSol 29 | 30 | 31 | def main(): 32 | s = Solution() 33 | print s.solveNQueens(4) 34 | 35 | 36 | if __name__ == "__main__": 37 | main() 38 | -------------------------------------------------------------------------------- /python/52_N-Queens_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | 5 | 6 | class Solution(object): 7 | def totalNQueens(self, n): 8 | def isValid(irow, icol, cols): 9 | for row, col in enumerate(cols): 10 | if icol == col or abs(irow - row) == abs(icol - col): 11 | return False 12 | return True 13 | def dfs(irow, cols): 14 | if irow == n: 15 | allSol[0] += 1 16 | return 17 | for icol in range(n): 18 | if isValid(irow, icol, cols): 19 | dfs(irow + 1, cols + [icol]) 20 | 21 | allSol = [0] 22 | dfs(0, []) 23 | return allSol[0] 24 | 25 | 26 | 27 | 28 | def main(): 29 | s = Solution() 30 | print s.totalNQueens(4) 31 | 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /python/53_Maximum_Subarray.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | ''' 6 | For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 7 | the contiguous subarray [4,-1,2,1] has the largest sum = 6. 8 | ''' 9 | 10 | class Solution(object): 11 | def maxSubArray(self, nums): 12 | # dp[i] : the sum of the maximum subarray ended at i 13 | n = len(nums) 14 | if not n: 15 | return None 16 | dp = [0 for i in range(n)] 17 | dp[0] = nums[0] 18 | maxSum = nums[0] 19 | for i in range(1, n): 20 | dp[i] = dp[i - 1] + nums[i] if dp[i - 1] > 0 else nums[i] 21 | maxSum = max(maxSum, dp[i]) 22 | return maxSum 23 | 24 | 25 | 26 | def main(): 27 | s = Solution() 28 | nums = [-2,1,-3,4,-1,2,1,-5,4] 29 | print s.maxSubArray(nums) 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /python/55_Jump_Game.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def canJump(self, A): 7 | n = len(A) 8 | if n <= 1: 9 | return True 10 | maxIdx = 0 11 | for i in range(n - 1): 12 | maxIdx = max(maxIdx, i + A[i]) 13 | if maxIdx < i + 1: 14 | break 15 | if maxIdx >= n - 1: 16 | return True 17 | return False 18 | 19 | 20 | 21 | def main(): 22 | s = Solution() 23 | #print s.canJump([2,3,1,1,4]) 24 | #print s.canJump([3,2,1,0,4]) 25 | print s.canJump([0, 2, 3]) 26 | 27 | if __name__ == "__main__": 28 | main() 29 | -------------------------------------------------------------------------------- /python/56_Merge_Intervals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | """ 5 | Given [1,3],[2,6],[8,10],[15,18], 6 | return [1,6],[8,10],[15,18]. 7 | """ 8 | 9 | # Definition for an interval. 10 | class Interval(object): 11 | def __init__(self, s=0, e=0): 12 | self.start = s 13 | self.end = e 14 | 15 | class Solution(object): 16 | def merge(self, intervals): 17 | if len(intervals) <= 1: 18 | return intervals 19 | intervals = sorted(intervals, key=lambda x:x.start) # remember 20 | res = [intervals[0]] 21 | for i in range(1, len(intervals)): 22 | if res[-1].end < intervals[i].start: 23 | res.append(intervals[i]) 24 | else: 25 | res[-1].end = max(intervals[i].end, res[-1].end) # [[1,4], [2,3]] 26 | return res 27 | 28 | 29 | 30 | def main(): 31 | s = Solution() 32 | i1 = Interval(1, 4) 33 | i2 = Interval(1, 4) 34 | a = [i1, i2] 35 | print s.merge(a) 36 | 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /python/57_Insert_Interval.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | 5 | class Solution(object): 6 | def insert(self, intervals, newInterval): 7 | if len(intervals) == 0: 8 | return [newInterval] 9 | for i in range(len(intervals)): 10 | if intervals[i].start > newInterval.start: 11 | loc = i # binary search would be better, just skip it 12 | break 13 | if intervals[-1].start <= newInterval.start: loc = i + 1 14 | res = [newInterval] 15 | for i in range(loc, 0, -1): 16 | if intervals[i - 1].end >= res[0].start: 17 | res[0].start = intervals[i - 1].start 18 | res[0].end = max(res[0].end, intervals[i - 1].end) 19 | else: 20 | res.insert(0, intervals[i - 1]) 21 | 22 | for i in range(loc, len(intervals)): 23 | if res[-1].end >= intervals[i].start: 24 | res[-1].end = max(intervals[i].end, res[-1].end) 25 | else: 26 | res.append(intervals[i]) 27 | return res 28 | 29 | 30 | 31 | 32 | 33 | def main(): 34 | s = Solution() 35 | s.insert() 36 | 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /python/58_Length_of_Last_Word.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | 6 | class Solution(object): 7 | def lengthOfLastWord(self, s): 8 | n = len(s) 9 | length, tag = 0, 1 10 | for i in range(n - 1, -1, -1): 11 | if s[i] == ' ' and tag: 12 | continue 13 | elif s[i] == ' ' and not tag: 14 | break 15 | if s[i] != ' ': 16 | tag = 0 17 | length += 1 18 | 19 | return length 20 | 21 | 22 | 23 | 24 | def main(): 25 | s = Solution() 26 | print s.lengthOfLastWord("abc deffa ") 27 | 28 | if __name__ == "__main__": 29 | main() 30 | -------------------------------------------------------------------------------- /python/59_Spiral_Matrix_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Solution(object): 4 | def generateMatrix(self, n): 5 | left, top = [0] * 2 6 | right, down = [n - 1] * 2 7 | direction = 0 8 | res = [[0] * n for i in range(n)] 9 | number = 1 10 | while 1: 11 | if direction == 0: 12 | for i in range(left, right + 1): 13 | res[top][i] = number 14 | number += 1 15 | top += 1 16 | if direction == 1: 17 | for i in range(top, down + 1): 18 | res[i][right] = number 19 | number += 1 20 | right -= 1 21 | if direction == 2: 22 | for i in range(right, left - 1, -1): 23 | res[down][i] = number 24 | number += 1 25 | down -= 1 26 | 27 | if direction == 3: 28 | for i in range(down, top - 1, -1): 29 | res[i][left] = number 30 | number += 1 31 | left += 1 32 | if number == n ** 2 + 1: 33 | break 34 | direction = (direction + 1) % 4 35 | return res 36 | 37 | 38 | 39 | 40 | 41 | 42 | def main(): 43 | s = Solution() 44 | print s.generateMatrix(3) 45 | 46 | if __name__ == "__main__": 47 | main() -------------------------------------------------------------------------------- /python/60_Permutation_Sequence.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | 4 | class Solution(object): 5 | def getPermutation(self, n, k): 6 | factorial = 1 7 | for i in range(1, n): 8 | factorial *= i 9 | if k > factorial * n: 10 | return -1 11 | k -= 1 12 | sets = [1, 2, 3, 4, 5, 6, 7, 8, 9] 13 | tag, res = 0, "" 14 | 15 | while k >= 0 and tag < n: 16 | tag += 1 17 | quotient = k / factorial 18 | k -= quotient * factorial 19 | res += str(sets[quotient]) 20 | sets.remove(sets[quotient]) 21 | if n == tag: 22 | factorial = 1 23 | else: 24 | factorial /= (n - tag) 25 | return res 26 | 27 | 28 | def main(): 29 | s = Solution() 30 | print s.getPermutation(4, 9) 31 | 32 | if __name__ == "__main__": 33 | main() -------------------------------------------------------------------------------- /python/61_Rotate_List.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Solution(object): 4 | def rotateRight(self, head, k): 5 | if not head: 6 | return head 7 | n = 0 8 | p, q = head, head 9 | while head: 10 | n += 1 11 | if p.next: 12 | p = p.next 13 | else: 14 | break 15 | if k == n: 16 | return head 17 | else: 18 | p.next = head 19 | k = k % n 20 | for i in range(1, n - k): 21 | q = q.next 22 | head = q.next 23 | q.next = None 24 | return head 25 | 26 | 27 | 28 | def main(): 29 | s = Solution() 30 | 31 | if __name__ == "__main__": 32 | main() -------------------------------------------------------------------------------- /python/62_Unique_Paths.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Solution(object): 4 | def uniquePaths(self, m, n): 5 | dp = [[0] * (n + 1) for i in range(m + 1)] 6 | for i in range(n + 1): 7 | dp[1][i] = 1 8 | for i in range(1, m + 1): 9 | dp[i][1] = 1 10 | if m == 1 or n == 1: 11 | return 1 12 | for i in range(1, m): 13 | for j in range(1, n): 14 | dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] 15 | return dp[m][n] 16 | 17 | 18 | 19 | def main(): 20 | s = Solution() 21 | print s.uniquePaths(2, 2) 22 | 23 | if __name__ == "__main__": 24 | main() -------------------------------------------------------------------------------- /python/63_Unique_Paths_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | 4 | class Solution(object): 5 | def uniquePathsWithObstacles(self, obstacleGrid): 6 | m = len(obstacleGrid) 7 | n = len(obstacleGrid[0]) 8 | dp = [[0] * n for i in range(m)] 9 | dp[0][0] = 1 - obstacleGrid[0][0] 10 | for i in range(1, n): 11 | dp[0][i] = dp[0][i - 1] * (1 - obstacleGrid[0][i]) 12 | for i in range(1, m): 13 | dp[i][0] = dp[i - 1][0] * (1 - obstacleGrid[i][0]) 14 | for i in range(m - 1): 15 | for j in range(n - 1): 16 | dp[i + 1][j + 1] = dp[i + 1][j] * (1 - obstacleGrid[i + 1][j]) + dp[i][j + 1] * (1 - obstacleGrid[i][j + 1]) 17 | return dp[m - 1][n - 1] * (1 - obstacleGrid[m - 1][n - 1]) 18 | 19 | 20 | 21 | def main(): 22 | s = Solution() 23 | #obstacleGrid = [[0,0,0], [0,1,0],[0,0,0]] 24 | obstacleGrid = [[1]] 25 | print s.uniquePathsWithObstacles(obstacleGrid) 26 | 27 | if __name__ == "__main__": 28 | main() -------------------------------------------------------------------------------- /python/64_Minimum_Path_Sum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Solution(object): 4 | def minPathSum(self, grid): 5 | m = len(grid) 6 | n = len(grid[0]) 7 | dp = [[0] * n for i in range(m)] 8 | dp[0][0] = grid[0][0] 9 | for i in range(m - 1): 10 | dp[i + 1][0] = dp[i][0] + grid[i + 1][0] 11 | for j in range(n - 1): 12 | dp[0][j + 1] = dp[0][j] + grid[0][j + 1] 13 | for i in range(m - 1): 14 | for j in range(n - 1): 15 | dp[i + 1][j + 1] = min(dp[i + 1][j], dp[i][j + 1]) + grid[i + 1][j + 1] 16 | return dp[m - 1][n - 1] 17 | 18 | def main(): 19 | s = Solution() 20 | grid = [[1,2,3], [4, 2, 1]] 21 | 22 | print s.minPathSum(grid) 23 | 24 | if __name__ == "__main__": 25 | main() -------------------------------------------------------------------------------- /python/66_Plus_One.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def plusOne(self, digits): 7 | carry = 1 8 | for i in range(len(digits) - 1, -1, -1): 9 | sums = carry + digits[i] 10 | carry = sums / 10 11 | digits[i] = sums % 10 12 | if carry: 13 | digits = [1] + digits 14 | return digits 15 | 16 | 17 | def main(): 18 | s = Solution() 19 | 20 | if __name__ == "__main__": 21 | main() 22 | -------------------------------------------------------------------------------- /python/67_Add_Binary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | ''' 6 | a = "11" 7 | b = "1" 8 | Return "100". 9 | ''' 10 | 11 | class Solution(object): 12 | def addBinary(self, a, b): 13 | if (len(a) < len(b)): 14 | return self.addBinary(b, a) 15 | 16 | m, n = len(a), len(b) 17 | carry = 0 18 | res = [] 19 | for i in range(m): 20 | if i > n - 1: 21 | total = int(a[m - 1 -i]) + int(carry) 22 | else: 23 | total = int(a[m - 1 -i]) + int(b[n - 1 -i]) + carry 24 | carry = total / 2 25 | #print i, a[i], b[], total, total % 2 26 | res.append(str(total % 2)) 27 | res = "".join(res) 28 | res = res[::-1] 29 | if carry: 30 | res = "1" + res 31 | return res 32 | 33 | 34 | def main(): 35 | s = Solution() 36 | print s.addBinary("1010", "1011") 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /python/69_sqrt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Solution(object): 4 | def mySqrt(self, x): 5 | if x < 1: 6 | return 0 7 | elif x < 4: 8 | return 1 9 | left, right = 1, x 10 | while left < right - 1: 11 | mid = (left + right) / 2 12 | if mid ** 2 == x: 13 | return mid 14 | if mid ** 2 > x: 15 | right = mid 16 | else: 17 | left = mid 18 | return left 19 | 20 | 21 | def main(): 22 | s = Solution() 23 | print s.mySqrt(16) 24 | 25 | if __name__ == "__main__": 26 | main() -------------------------------------------------------------------------------- /python/70_Climbing_Stairs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | ''' 6 | You are climbing a stair case. It takes n steps to reach to the top. 7 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 8 | ''' 9 | 10 | class Solution(object): 11 | def climbStairs(self, n): 12 | # dp i: number of ways to climb to a i-stair 13 | if n <= 2: 14 | return n 15 | dp = [0 for i in range(n + 1)] 16 | dp[1], dp[2] = 1, 2 17 | for i in range(3, n + 1): 18 | #print i 19 | dp[i] = dp[i - 1] + dp[i - 2] 20 | return dp[n] 21 | 22 | 23 | 24 | def main(): 25 | s = Solution() 26 | print s.climbStairs(4) 27 | 28 | if __name__ == "__main__": 29 | main() 30 | -------------------------------------------------------------------------------- /python/71_Simplify_Path.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Solution(object): 4 | def simplifyPath(self, path): 5 | path += "/" 6 | res, part = "", "" 7 | vec = [] 8 | for i in range(len(path)): 9 | if path[i] != '/': 10 | part += path[i] 11 | else: 12 | if part == "": 13 | continue 14 | elif part == "..": 15 | if vec == []: 16 | part = "" 17 | continue 18 | vec.pop() 19 | elif part != ".": 20 | vec.append(part) 21 | part = "" 22 | for i in range(len(vec)): 23 | res += "/" + vec[i] 24 | if vec == []: 25 | res = "/" 26 | return res 27 | 28 | 29 | def main(): 30 | s = Solution() 31 | print s.simplifyPath("/...") 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /python/72_Edit_Distance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | 5 | class Solution(object): 6 | def minDistance(self, word1, word2): 7 | m, n = len(word1), len(word2) 8 | dp = [[0] * (n + 1) for _ in range(m + 1)] 9 | for i in range(1, m + 1): 10 | dp[i][0] = i 11 | for i in range(1, n + 1): 12 | dp[0][i] = i 13 | 14 | for i in range(1, m + 1): 15 | for j in range(1, n + 1): 16 | if word1[i-1] != word2[j-1]: 17 | dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 18 | else: 19 | dp[i][j] = dp[i-1][j-1] 20 | return dp[m][n] 21 | 22 | 23 | 24 | class TestSolution(unittest.TestCase): 25 | def setUp(self): 26 | self.s = Solution() 27 | 28 | def test_method(self): 29 | """Such as self.assertEqual, self.assertTrue""" 30 | #self.assertEqual(self.s.) 31 | pass 32 | 33 | def main(): 34 | s = Solution() 35 | 36 | 37 | if __name__ == "__main__": 38 | unittest.main() 39 | -------------------------------------------------------------------------------- /python/73_Set_Matrix_Zeroes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | 4 | class Solution(object): 5 | def setZeroes(self, matrix): 6 | m = len(matrix) 7 | n = len(matrix[0]) 8 | tagRow = [0] * m 9 | tagCol = [0] * n 10 | for i in range(m): 11 | for j in range(n): 12 | if matrix[i][j] == 0: 13 | tagRow[i], tagCol[j] = 1, 1 14 | for i in range(m): 15 | for j in range(n): 16 | if tagRow[i] or tagCol[j]: 17 | matrix[i][j] = 0 18 | 19 | 20 | def main(): 21 | s = Solution() 22 | 23 | if __name__ == "__main__": 24 | main() 25 | -------------------------------------------------------------------------------- /python/74_Search_a_2D_Matrix.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | ''' 4 | [ 5 | [1, 3, 5, 7], 6 | [10, 11, 16, 20], 7 | [23, 30, 34, 50] 8 | ] 9 | Given target = 3, return true. 10 | ''' 11 | 12 | class Solution(object): 13 | def searchMatrix(self, matrix, target): 14 | m = len(matrix) 15 | n = len(matrix[0]) 16 | left, right = 0, m * n - 1 17 | 18 | while left <= right: 19 | mid = (left + right) / 2 20 | i0 = mid / n 21 | j0 = mid % n 22 | if matrix[i0][j0] == target: 23 | return True 24 | elif matrix[i0][j0] < target: 25 | left = mid + 1 26 | else: 27 | right = mid - 1 28 | return False 29 | 30 | 31 | 32 | 33 | def main(): 34 | s = Solution() 35 | matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]] 36 | #matrix = [[1, 2, 4]] 37 | print s.searchMatrix(matrix, 4) 38 | 39 | if __name__ == "__main__": 40 | main() 41 | -------------------------------------------------------------------------------- /python/75_Sort_Colors.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Solution(object): 4 | def sortColors(self, nums): 5 | n = len(nums) 6 | i, left, right = 0, 0, n - 1 7 | while i < n: 8 | tmp = nums[i] 9 | if nums[i] == 0 and i >= left: 10 | nums[left], nums[i] = tmp, nums[left] 11 | left += 1 12 | i += 1 13 | elif nums[i] == 2 and i < right: 14 | nums[right], nums[i] = tmp, nums[right] 15 | right -= 1 16 | else: 17 | i += 1 18 | def main(): 19 | s = Solution() 20 | num = [2] 21 | s.sortColors(num) 22 | print num 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /python/78_Subsets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | 4 | class Solution(object): 5 | def subsets(self, nums): 6 | num = sorted(nums) 7 | res = [[]] 8 | part = [] 9 | def dfs(num, part): 10 | if len(num) == 0: 11 | return 12 | for i, item in enumerate(num): 13 | res.append(part + [item]) 14 | dfs(num[i + 1:], part + [item]) 15 | dfs(num, part) 16 | return res 17 | 18 | 19 | 20 | def main(): 21 | s = Solution() 22 | nums = [2,1,3] 23 | print s.subsets(nums) 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /python/79_Word_Search.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Solution(object): 4 | def exist(self, board, word): 5 | m, n = len(board), len(board[0]) 6 | if not m or not n: 7 | return False 8 | track = [[0] * n for i in range(m)] 9 | for i in range(m): 10 | for j in range(n): 11 | if self.dfs(board, i, j, track, word, 0, m, n): 12 | return True 13 | return False 14 | 15 | def dfs(self, board, i, j, track, word, index, m, n): 16 | if index == len(word): 17 | return True 18 | if i < 0 or i >= m or j < 0 or j >= n or board[i][j] != word[index] or track[i][j]: 19 | return False 20 | track[i][j] = 1 21 | # important, if only one of 4 directions works, then match 22 | if self.dfs(board, i + 1, j, track, word, index + 1, m, n): return 1 23 | if self.dfs(board, i - 1, j, track, word, index + 1, m, n): return 1 24 | if self.dfs(board, i, j + 1, track, word, index + 1, m, n): return 1 25 | if self.dfs(board, i, j - 1, track, word, index + 1, m, n): return 1 26 | track[i][j] = 0 # important, recover tag when we haven't tried that route. 27 | return False 28 | 29 | 30 | def main(): 31 | s = Solution() 32 | dat = ["CAA", 33 | "AAA", 34 | "BCD"] 35 | print s.exist(dat, "AAB") 36 | 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /python/80_Remove_Duplicates_from_Sorted_Array_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | ''' 4 | [1,1,1,2,2,3], return 5 5 | ''' 6 | 7 | class Solution(object): 8 | def removeDuplicates(self, nums): 9 | n = len(nums) 10 | if n < 3: 11 | return n 12 | total = 2 13 | i = 2 14 | while i < n: 15 | if nums[i] == nums[i - 2]: 16 | nums.remove(nums[i]) 17 | n -= 1 18 | continue 19 | total += 1 20 | i += 1 21 | return total 22 | 23 | def main(): 24 | s = Solution() 25 | print s.removeDuplicates([1,1,1,2]) 26 | 27 | if __name__ == "__main__": 28 | main() 29 | -------------------------------------------------------------------------------- /python/82_Remove_Duplicates_from_Sorted_List_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def deleteDuplicates(self, head): 7 | if (not head or not head->next) 8 | return head 9 | p = ListNode(0) 10 | p.next = head 11 | left = p 12 | right = head 13 | tag = 0 14 | while right: 15 | if right.next and right.next.val == right.val: 16 | right.next = right.next.next 17 | tag = 1 18 | elif tag: 19 | left.next = right.next 20 | right = right.next 21 | tag = 0 22 | else: 23 | left = right 24 | right = right.next 25 | return p.next 26 | 27 | 28 | 29 | 30 | def main(): 31 | s = Solution() 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /python/83_Remove_Duplicates_from_Sorted_List.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class Solution(object): 6 | def deleteDuplicates(self, head): 7 | if head == None: 8 | return head 9 | tmp = head 10 | while tmp.next: 11 | if tmp.next.val == tmp.val: 12 | tmp.next = tmp.next.next 13 | else: 14 | tmp = tmp.next 15 | return head 16 | 17 | 18 | 19 | 20 | 21 | def main(): 22 | s = Solution() 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /python/86_Partition_List.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | class Solution(object): 11 | def partition(self, head, x): 12 | lt = ListNode(0) 13 | ge = ListNode(0) 14 | geHead = ge 15 | lt.next = head 16 | head = lt 17 | 18 | while lt.next: 19 | if lt.next.val < x: 20 | lt = lt.next 21 | else: 22 | ge.next = lt.next 23 | lt.next = lt.next.next 24 | ge = ge.next 25 | ge.next = None 26 | 27 | lt.next = geHead.next 28 | return head.next 29 | 30 | 31 | 32 | 33 | def main(): 34 | s = Solution() 35 | 36 | if __name__ == "__main__": 37 | main() 38 | -------------------------------------------------------------------------------- /python/87_Scramble_String.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | 5 | # https://discuss.leetcode.com/topic/42438/sharing-recursive-python-solution-with-memo-beats-99 6 | class Solution(object): 7 | def isScramble(self, s, t, memo={}): 8 | # Check with sorted is fundamental, otherwise TLE 9 | if len(s) != len(t) or sorted(s) != sorted(t): 10 | return False 11 | if len(s) <= 3: 12 | return True 13 | if s == t: 14 | return True 15 | if (s, t) in memo: 16 | return memo[s, t] 17 | n = len(s) 18 | for i in range(1, n): 19 | a = self.isScramble(s[:i], t[:i], memo) and self.isScramble(s[i:], t[i:], memo) 20 | if not a: 21 | b = self.isScramble(s[:i], t[-i:], memo) and self.isScramble(s[i:], t[:-i], memo) 22 | if a or b: 23 | memo[s, t] = True 24 | return True 25 | memo[s, t] = False 26 | return False 27 | 28 | 29 | 30 | def main(): 31 | s = Solution() 32 | print s.isScramble("rgtae", "great") 33 | 34 | 35 | if __name__ == "__main__": 36 | main() 37 | -------------------------------------------------------------------------------- /python/88_Merge_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | # the worst case of this method can be o(n2), no extra method needed 6 | class Solution(object): 7 | def merge(self, nums1, m, nums2, n): 8 | i, j, shift = [0] * 3 9 | while i < m + j and j < n: 10 | tmp = nums1[i] 11 | if nums2[j] < nums1[i]: 12 | for k in range(m + j, i, -1): 13 | nums1[k] = nums1[k - 1] 14 | nums1[i] = nums2[j] 15 | j += 1 16 | else: 17 | i += 1 18 | if m == 0: 19 | for i in range(n): 20 | nums1[i] = nums2[i] 21 | else: 22 | for i in range(m + j, m + n): 23 | nums1[i] = nums2[i - m] 24 | 25 | # we can also create a temp array with space o(m + n) 26 | 27 | def main(): 28 | s = Solution() 29 | num1 = [4,5,9,11,0,0,0,0,0,0,0,0,0] 30 | num2 = [1,3,6,15] 31 | s.merge(num1, 4, num2, 4) 32 | print num1 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /python/89_Gray_Code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | 4 | # 2 successive values differ in 1 bit 5 | class Solution: 6 | def grayCode(self, n): 7 | if n < 0: 8 | return [] 9 | res = [0] 10 | shift = 1 11 | for i in range(n): 12 | for j in range(len(res) - 1, -1, -1): 13 | res.append(res[j] + shift) 14 | shift = shift << 1 15 | return res 16 | 17 | def main(): 18 | s = Solution() 19 | print s.grayCode(3) 20 | 21 | if __name__ == "__main__": 22 | main() 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /python/90_Subsets_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Solution(object): 4 | def subsetsWithDup(self, nums): 5 | n = len(nums) 6 | nums = sorted(nums) 7 | res = [[]] 8 | part = [] 9 | def dfs(nums, part): 10 | if len(nums) == 0: 11 | return 12 | i, last = 0, "*" 13 | for i in range(len(nums)): 14 | if nums[i] == last: 15 | continue 16 | # can't append part first 17 | # since it would transfer address rather than value 18 | # so once innter list changes, res change too 19 | # part.append(nums[i]) 20 | res.append(part + [nums[i]]) 21 | dfs(nums[i + 1:], part + [nums[i]]) 22 | last = nums[i] 23 | dfs(nums, part) 24 | return res 25 | 26 | 27 | def main(): 28 | s = Solution() 29 | print s.subsetsWithDup([1,2,2]) 30 | 31 | 32 | if __name__ == "__main__": 33 | main() 34 | -------------------------------------------------------------------------------- /python/91_Decode_Ways.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | 5 | class Solution: 6 | def numDecodings(self, s): 7 | n = len(s) 8 | if s == "" or s[0]=='0': return 0 9 | dp = [0] * (n + 1) 10 | dp[0:2] = [1,1] 11 | for i in range(2,len(s)+1): 12 | if 10 <= int(s[i-2:i]) <=26 and s[i-1] != '0': 13 | dp[i] = dp[i-1] + dp[i-2] 14 | elif int(s[i-2:i]) == 10 or int(s[i-2:i]) == 20: 15 | dp[i] = dp[i-2] 16 | elif s[i-1] != '0': 17 | dp[i] = dp[i-1] 18 | else: 19 | return 0 20 | return dp[len(s)] 21 | 22 | 23 | class TestSolution(unittest.TestCase): 24 | def setUp(self): 25 | self.s = Solution() 26 | 27 | def test_method(self): 28 | """Such as self.assertEqual, self.assertTrue""" 29 | self.assertEqual(self.s.numDecodings("0"), 0) 30 | self.assertEqual(self.s.numDecodings("1"), 1) 31 | self.assertEqual(self.s.numDecodings("01"), 0) 32 | self.assertEqual(self.s.numDecodings("100"), 0) 33 | self.assertEqual(self.s.numDecodings("30"), 0) 34 | self.assertEqual(self.s.numDecodings("101"), 1) 35 | self.assertEqual(self.s.numDecodings("1212"), 5) 36 | pass 37 | 38 | 39 | if __name__ == "__main__": 40 | unittest.main() 41 | -------------------------------------------------------------------------------- /python/92_Reverse_Linked_List_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | 5 | class Solution(object): 6 | def reverseBetween(self, head, m, n): 7 | if m == n: 8 | return head 9 | p = ListNode(0) 10 | p.next = head 11 | head = p 12 | leftN, rightN = p, p 13 | for i in range(m): 14 | leftN = leftN.next 15 | if i != m - 1: 16 | p = p.next 17 | for j in range(n): 18 | rightN = rightN.next 19 | p.next = rightN # 1->4 20 | rightN = rightN.next 21 | for i in range(n - m, 0, -1): 22 | tmp = leftN 23 | for j in range(i - 1, 0, -1): 24 | tmp = tmp.next 25 | tmp.next.next = tmp 26 | leftN.next = rightN # 2->5 27 | return head.next 28 | 29 | 30 | 31 | 32 | class TestSolution(unittest.TestCase): 33 | def setUp(self): 34 | self.s = Solution() 35 | 36 | def test_method(self): 37 | """Such as self.assertEqual, self.assertTrue""" 38 | pass 39 | 40 | 41 | if __name__ == "__main__": 42 | unittest.main() -------------------------------------------------------------------------------- /python/94_Binary_Tree_Inorder_Traversal.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | def inorderTraversal(self, root): 14 | """ 15 | :type root: TreeNode 16 | :rtype: List[int] 17 | """ 18 | tmp = root 19 | res, stk = [], [] 20 | while tmp or stk != []: 21 | if tmp: 22 | stk.append(tmp) 23 | tmp = tmp.left 24 | else: 25 | tmp = stk[-1] 26 | stk.pop() 27 | res.push_back(tmp.val) 28 | tmp = tmp.right 29 | return res 30 | 31 | 32 | class TestSolution(unittest.TestCase): 33 | def setUp(self): 34 | self.s = Solution() 35 | 36 | def test_method(self): 37 | """Such as self.assertEqual, self.assertTrue""" 38 | pass 39 | 40 | 41 | if __name__ == "__main__": 42 | unittest.main() -------------------------------------------------------------------------------- /python/95_Unique_Binary_Search_Trees_II.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | class Solution(object): 5 | def generateTrees(self, n): 6 | if n == 0: 7 | return [] 8 | return self.dfs(1, n) 9 | 10 | def dfs(self, Tmin, Tmax): 11 | if Tmin > Tmax: 12 | return [None] 13 | resList = [] 14 | # generate leftSubTree and rightSubTree 15 | for k in range(Tmin, Tmax + 1): 16 | leftSubTree = self.dfs(Tmin, k - 1) 17 | rightSubTree = self.dfs(k + 1, Tmax) 18 | 19 | for i in leftSubTree: 20 | for j in rightSubTree: 21 | rootNote = TreeNode(k) 22 | rootNote.left = i 23 | rootNote.right = j 24 | resList.append(rootNote) 25 | return resList 26 | 27 | 28 | 29 | class TestSolution(unittest.TestCase): 30 | def setUp(self): 31 | self.s = Solution() 32 | 33 | def test_method(self): 34 | """Such as self.assertEqual, self.assertTrue""" 35 | self.assertEqual(self.s.numTrees(1), 1) 36 | self.assertEqual(self.s.numTrees(2), 2) 37 | pass 38 | 39 | 40 | if __name__ == "__main__": 41 | unittest.main() -------------------------------------------------------------------------------- /python/96_Unique_Binary_Search_Trees.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | 5 | 6 | class Solution(object): 7 | def numTrees(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | dp = [0] * (n + 1) 13 | dp[0] = 1 14 | for i in range(1, n + 1): 15 | for j in range(i): 16 | dp[i] += dp[j] * dp[i - 1 - j] 17 | return dp[n] 18 | 19 | 20 | class TestSolution(unittest.TestCase): 21 | def setUp(self): 22 | self.s = Solution() 23 | 24 | def test_method(self): 25 | """Such as self.assertEqual, self.assertTrue""" 26 | #self.assertEqual(self.s.) 27 | pass 28 | 29 | 30 | if __name__ == "__main__": 31 | unittest.main() 32 | -------------------------------------------------------------------------------- /python/98_Validate_Binary_Search_Tree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import unittest 3 | 4 | 5 | class Solution(object): 6 | def isValidBST(self, root): 7 | if root: 8 | return self.check(root, -10 ** 10, 10 ** 10) 9 | else: 10 | return True 11 | 12 | def check(self, root, Tmin, Tmax): 13 | leftValid, rightValid = True, True 14 | 15 | if Tmin >= root.val or root.val >= Tmax: 16 | return False 17 | if root.left: 18 | leftValid = self.check(root.left, Tmin, root.val) 19 | if root.right: 20 | rightValid = self.check(root.right, root.val, Tmax) 21 | 22 | return (leftValid and rightValid) 23 | 24 | 25 | 26 | class TestSolution(unittest.TestCase): 27 | def setUp(self): 28 | self.s = Solution() 29 | 30 | def test_method(self): 31 | """Such as self.assertEqual, self.assertTrue""" 32 | #self.assertEqual(self.s.) 33 | pass 34 | 35 | def main(): 36 | s = Solution() 37 | 38 | 39 | if __name__ == "__main__": 40 | unittest.main() 41 | -------------------------------------------------------------------------------- /python/99_Recover_Binary_Search_Tree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | import os 4 | 5 | class TreeNode(object): 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | class Solution(object): 12 | def recoverTree(self, root): 13 | self.first = None 14 | self.second = None 15 | self.prev = None 16 | self.inorder(root) 17 | tmp = self.first.val 18 | self.first.val = self.second.val 19 | self.second.val = tmp 20 | return 21 | 22 | def inorder(self, root): 23 | if not root: 24 | return 25 | else: 26 | self.inorder(root.left) 27 | if not self.prev: 28 | self.prev = root 29 | else: 30 | if self.prev.val >= root.val: 31 | if not self.first: 32 | self.first = self.prev 33 | self.second = root 34 | self.prev = root 35 | self.inorder(root.right) 36 | 37 | 38 | def main(): 39 | s = Solution() 40 | 41 | t = [TreeNode(i) for i in range(1, 8)] 42 | t[3].left = t[1] 43 | t[3].right = t[5] 44 | t[1].left = t[0] 45 | t[1].right = t[2] 46 | t[5].left = t[4] 47 | t[5].right = t[6] 48 | print s.recoverTree(t[3]) 49 | 50 | if __name__ == "__main__": 51 | main() 52 | -------------------------------------------------------------------------------- /upload.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | num=$1 4 | echo "add question " $num 5 | if [ -f ./c++/${num}_*[^.cpp] ] 6 | then 7 | rm ./c++/${num}_*[^.cpp] # delete executable file 8 | fi 9 | git add ./c++/${num}_*.cpp 10 | #git add ./python/${num}*.py 11 | 12 | if [ $# -eq 0 ] 13 | then 14 | echo "Input the question number!" 15 | elif [ $# -eq 1 ] 16 | then 17 | echo "You haven't commit the task!" 18 | else 19 | len=${#num} 20 | echo $n 21 | if [ $len -eq 3 ] 22 | then 23 | cmt=`expr substr "$*" 4 100` # get the 2nd-100th parameters as commit 24 | elif [ $len -eq 2 ] 25 | then 26 | cmt=`expr substr "$*" 3 100` # get the 2nd-100th parameters as commit 27 | elif [ $len -eq 1 ] 28 | then 29 | cmt=`expr substr "$*" 2 100` # get the 2nd-100th parameters as commit 30 | fi 31 | 32 | cmt=''$cmt'' 33 | echo $cmt 34 | git commit -m "${cmt}" 35 | git push 36 | fi 37 | 38 | 39 | --------------------------------------------------------------------------------