[Algorithm] The most understandable greedy algorithm explanation (with examples)

1. Definition

Greedy algorithm, defined as : dismantling a large problem into several small problems, in each step of solving the problem, no matter what impact the current decision at this step will have on the future, only the immediate decision is optimal That's it. This is repeated until the optimal solution is finally obtained.

Defect : I just want to get the optimal solution. Although each step is the optimal solution, it may not be able to get the optimal solution as a whole.

Advantages : The time complexity is usually relatively low , that is, it takes less time. The whole may not be the best, but it is also close to ten .


Two, examples

There are such a bunch of numbers, arranged according to the pyramid, as shown in the figure below. We start from the vertex and find the sum of the largest paths from top to bottom; in other words, add a number to each layer from top to bottom to make this number the largest.

If you look at it with your eyes, it is easier to see that the best path is 9-7-3-4-5, but if you count too many, it will not work well, and you have to rely on code to calculate it.

There is a solution that calculates every possible possibility and brute-forces it, which is also simple to write. But obviously this is very time-consuming and memory-consuming, and the computer will be stuck every minute, so here we use the greedy algorithm .


3. Code

We represent this pyramid array as a[i][j], simply write a code as follows:

// 注意,下面的代码只是表意,不能直接扒过去用
// a[i][j]表示数组,maxJ表示数组的最大层数,temp表示临时数值
// maxJ表示总列数,maxI表示当前列的最大行数

for(j=0; j<maxJ; j++){
    for(i=0; i<maxI; i++){
        temp1 = a[i][j] + a[i][j+1];
        temp2 = a[i][j] + a[i+1][j+1];
        temp = max(temp1, temp2);
    }
    maxSum = maxSum + temp;
}
return maxSum;

Guess you like

Origin blog.csdn.net/m0_55080712/article/details/124675250