码迷,mamicode.com
首页 > 其他好文 > 详细

蛮力法

时间:2015-07-28 10:37:03      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

蛮力法就是以最直观、最直接,从头到尾,从上到下的思维去尝试解决问题。

它主要包括以下三种方式:

  1. 一个一个地解决:冒泡排序
  2. 尝试所有可能的迭代:顺序查找、模式匹配
  3. 尝试所有的排列组合:最近点对、背包问题
// 冒泡排序
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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!