标签:
蛮力法就是以最直观、最直接,从头到尾,从上到下的思维去尝试解决问题。
它主要包括以下三种方式:
// 冒泡排序 void bubble_sort(array[0,..,n]) { for i=0 to i=n-2: // i表示冒第几个泡 for j=0 to j=n-2-i: if array[j] > array[j+1]: swap(array[j], array[j+1]) }
/* * 模式匹配 * 直接思路: * 蛮力法,一个个元素比较;不成功后,再往后移动一位,继续比较 */ #include <string> using namespace std; void matchPatternByForce(string str, string pattern) { 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") return str_ptr-str.begin(); str_ptr++; return -1; }
/* * 背包问题 * 思路: * 蛮力法:总排列数是2的n次方;通过位图表示,来确定每一个元素是否存在组合中 */ #include <vector> #include <iostream> #include <string> using namespace std; /* 蛮力法 */ int findFittestByBitMap(capacity, things[0, n]) { allPossbilities = 2 << n; for loop_num=0 to loop_num=allPossbilities: bit_pos = 0; sum_value = 0; max_value = 0; while loop_num > 0: bit_value = loop_num % 2; loop_num = loop_num / 2; if bit_value: sum_value += bit_value; if sum_value <= capacity && sum_value > max_value: max_value = sum_value; return max_value; }
标签:
原文地址:http://www.cnblogs.com/johnchow/p/4681863.html