The easiest to understand violent recursion and dynamic programming in history~~

            

        The easiest to understand brute force recursion and dynamic programming in history ~~



    Introduction to recursion and dynamic programming


Brute-force recursion:
1. Transform the problem into
a subproblem of the same type that is reduced in size
2. Have a clear base case that does not require recursion
3. Have a decision-making process when the result of the subproblem is obtained

4. Do not record the solution of each sub-problem (different from dynamic programming 2)


Dynamic programming
1, come from violent recursion
2, record the solution of each sub-problem, avoid repeated calculation
3, abstract the process of violent recursion into state expression

4, and there is a possibility to simplify the state expression to make it more concise


Dynamic programming is actually evolved from violent recursion, and each dynamic programming connection can basically find its dynamic programming version~

Their relationship is as follows:

Violent recursion------"dependency relationship (routine, that is, memory relationship)------"dynamic programming


The following is an example to give you a detailed introduction:


First understand the meaning of the title:

Given an array and an integer, you can choose the numbers in the arr array at will, and see if you can get the aim if you add them up. If you can get it, return true, if you can't return false

eg : arr[] = { 3, 2, 9, 7 }; Aim = 21; return true 3+2+9+7=21

        arr[] = { 3, 2, 9, 7 }; Aim = 13; returns false, cannot be combined to get 13



Thought analysis:

First use brute force recursion to solve:


Let's take a look at the parameters of the method first. The parameters are arr[] and Aim, which are provided by the title. We define i and sum. What do these two parameters mean?

Their meaning is that in an array, starting from the i subscript, you can arbitrarily go to the numbers after i for accumulation, and the accumulated sum is sum, see the figure:



If you can think of this picture or see this picture, you have already succeeded in half~~

可以发现,要判断这个数组中是否有满足要求的组合,只要看最后一行是否有相应的aim值就可以了。

所以,就有了下面的暴力递归:



暴力递归之后,就是动态规划了~

来来来,重点来了,从暴力递归转变到动态规划,跟题意是没有半毛钱关系的~

下面划重点了:

暴力递归------》依赖关系(套路,即记忆关系)------》动态规划

这里还差了个依赖关系:

啥都别说了,先画个图吧嘻嘻~

还是以上面那个例子为主:

arr[3] = {2,3,7};

aim = 10;

那么i的取值范围就是0~3了

sum的取值则是2+3+7=12即(0~12)

先看暴力破解法的basecase:


辣么,第三行sum等于Aim的值就为true,其他为false;

再看基本关系:


通过细细分析,可以得到下面的依赖关系图了~

图中的方框加×是(i,sum)的依赖,也就是说,要想得到(I,sum)的值,只要知道两个方框加×里面的值就可以推出来了( 不是我说的,是程序里面体现出来的)那么,因为第三列的值都知道了,那么其他列的值肯定也可以通过这一列的值推出来,那么我们所要求的(0,0)的值不就出来了吗?


这个依赖关系出来之后,那么动态规划的解也就出来了~~~(开心)


其实这个方法我也是思考了很久才领悟的~

希望对你们也能有所帮助~~不懂欢迎留言,懂得帮忙点个赞~~~

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325727023&siteId=291194637