算法学习笔记-暴力搜索和分治法

1.今天学习了一个简单的求最大连续子数组的问题,给定一个数组A[0,…,n-1],求A的连续子数 组,使得该子数组的和最大。例如:数组: 1, -2, 3, 10, -4, 7, 2, -5

Python暴力求解法:

dest_arry = [1,-2,3,10,-4,7,-2,5,12]
max_val = dest_arry[0]
cuur_val = 0

start = 0
end = 0


print (len(dest_arry))

count = len(dest_arry)
#暴力法
for i in range(0, count):
    for j in range(i, count):
        cuur_val = 0
        for k in range(i, j+1):          #这个需要特别注意,在这里这句话的意思相当于是for( k=i,k<(j+1),k++),在python中没有'<='这个符号
            cuur_val = cuur_val + dest_arry[k]
            if(cuur_val > max_val):
                max_val = cuur_val
                start = i
                end = k

print (max_val, start,end)

Python分治法:

#分治法
dest_arry = [1,-2,3,10,-4,7,-2,5,12]

max_val = dest_arry[0]
cuur_val = 0

start = 0
end = 0


print (len(dest_arry))

count = len(dest_arry)

def max_sub_add(fr, to):
    global start
    global end

    if fr == to:
        return dest_arry[fr]
    mid = int((fr + to)/2)
    m1 = max_sub_add(fr, mid)
    m2 = max_sub_add(mid+1, to)


    left = dest_arry[mid]
    now = dest_arry[mid]

    i = mid - 1
    while(i>=fr):
        now = now + dest_arry[i]
        if(now > left):
            left = now
            start = i
        i = i - 1

    right = dest_arry[mid+1]
    now = dest_arry[mid+1]

    i = mid+2
    while(i <= to):
        now = now + dest_arry[i]
        if (now> right):
            right = now
            end = i
        i = i + 1
    # for i in range(mid+2, to+1):
    #     now = now + dest_arry[i]
    #     if (now> right):
    #         right = now
    #         end = i


    m3 = right + left
    return max(m1, m2, m3)

start = 0
end = 0

result = max_sub_add(0, (count)-1)
print(result, start, end)

C/C++暴力法:

#include "stdio.h"
#include "stdlib.h"

void baoli()
{
    int dest_arry[] = {1,-2,3,10,-4,7,-2,5,-12};

    int max_val = dest_arry[0] , cuur_val = 0, start_nbr = 0, end_nbr = 0;
    int count =  sizeof(dest_arry) / sizeof(int);

    int i = 0, j = 0, k = 0;

    printf("count: %d \n", count);

    for( i = 0; i < count; i++)
    {
        for (j=i;j<count; j++)
        {
            cuur_val = 0;
            for (k=i; k<=j; k++)
            {
                cuur_val = cuur_val + dest_arry[k];
                if(cuur_val > max_val)
                {
                    max_val = cuur_val;
                    start_nbr = i;
                    end_nbr = k;
                   
                }
            }
        }
    }
   

    printf("start: %d  end_nbr: %d  max_val: %d\n", start_nbr, end_nbr, max_val);
   
}
int main()
{ 

    baoli();
    
}

 

posted @ 2018-07-04 22:24  badwell  阅读(975)  评论(0编辑  收藏  举报