Brute force method is the most intuitive, the most direct, from beginning to end, from top to bottom thinking to try to solve the problem.
It mainly consists of the following three ways:
- One-to-one solution: bubble sort
- Try all possible iterations: Sequential lookup, pattern matching
- Try all permutations: Nearest point pair, knapsack problem
// Bubble Sort void bubble_sort (array[0,.., N]) { for i=0 to i=n-2: // I mean take the first few bubbles for j=0 to j=n-2-i: if array[j] > array[j+1 ]: swap (array[j], array[j+1])}
/** Pattern Matching * Direct thinking: * Brute Force method, a comparison of elements; After unsuccessful, move back one bit, continue to compare*/#include<string>using namespacestd;voidMatchpatternbyforce (stringStrstringpattern) {Str_ptr= Str.begin (), pattern_ptr =Pattern.begin (); while(Str_ptr! ="\ n") str_ptr_tmp=str_ptr; while(Pattern_ptr! ="\ n") if(*str_ptr++! = *pattern_ptr++) Break; if(Pattern_ptr = ="\ n")returnstr_ptr-Str.begin (); Str_ptr++; return-1;}
/** Backpack Problem * Ideas: * Brute Force method: The total number of permutations is 2 of the N-square; by means of a bitmap representation to determine whether each element exists in a combination*/#include<vector>#include<iostream>#include<string>using namespacestd;/*Brute Force Method*/intFindfittestbybitmap (capacity, things[0, N]) {allpossbilities=2<<N; forloop_num=0To loop_num=Allpossbilities:bit_pos=0; Sum_value=0; Max_value=0; whileLoop_num >0: Bit_value= loop_num%2; Loop_num= Loop_num/2; ifBit_value:sum_value+=Bit_value; ifSum_value <= capacity && sum_value >Max_value:max_value=Sum_value; returnMax_value;}
Brute Force method