find cheapest path through array (recursion)

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

I'm currently working on recursion and i keep getting stuck at this question:

Find the cheapest path through an array using recursion. for example, if i had an array [0,1,3,4,1] i start at the value 0. Now i have 2 options i could jump to index 2 or just move to index 1.In this case i would jump right to index 2 (value 3) then jump to index 4 (value 1) because 3+1= 4 and that would be the cheapest way through the array.

I've tried to compare the move index value with the jump index value and see which is smallest but in this case that would not work because if i compare move value (1) with jump value (3), 1 is smallest and my program would take that as the correct path when in reality it is not and the 3 was a better option.

Thank you for taking the time to help!

回答1:

You can solve this problem using dynamic programming.Let's say we create one array dp, in which dp[i] represents min cost to reach at position i. We can fill this array upto size of input using following:

for(i=1;i<=len;i++)     //we can reach at current position either by i-1 or by i-2    //choose one which gives minimum cost and +arr[i] cost of current position    dp[i] = min(dp[i-1],dp[i-2])+arr[i] 

we can reach at ith position either by previous position by taking one move or by i-2 by taking a jump of 2.So in this way you can find the minimum cost to reach the final position.So dp[len] will be your minimum cost to reach at last position. There is one similar problem here



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!