📜  贪婪方法与动态编程

📅  最后修改于: 2021-04-27 23:36:22             🧑  作者: Mango

贪婪算法是一种算法范式,它一步一步地建立解决方案,总是选择提供最明显和最直接利益的下一个解决方案。因此,选择局部最优还会导致全局解决方案的问题最适合贪婪。

例如,考虑分数阶背包问题。局部最佳策略是选择具有最大值与重量比的项目。这种策略还导致了全局最优解,因为我们允许取零碎的东西。

动态编程主要是对纯递归的优化。只要看到递归解决方案重复调用相同输入的地方,就可以使用动态编程对其进行优化。这样做的想法是简单地存储子问题的结果,这样我们就不必在以后需要时重新计算它们。这种简单的优化降低了从指数到多项式的时间复杂度。例如,如果我们为斐波那契数写一个简单的递归解决方案,我们将得到指数时间复杂度,如果通过存储子问题的解决方案对其进行优化,则时间复杂度将降低为线性。

以下是贪婪方法与动态编程之间的一些主要区别:

Feature Greedy method Dynamic programming
Feasibility In a greedy Algorithm, we make whatever choice seems best at the moment in the hope that it will lead to global optimal solution. In Dynamic Programming we make decision at each step considering current problem and solution to previously solved sub problem to calculate optimal solution .
Optimality In Greedy Method, sometimes there is no such guarantee of getting Optimal Solution. It is guaranteed that Dynamic Programming will generate an optimal solution as it generally considers all possible cases and then choose the best.
Recursion A greedy method follows the problem solving heuristic of making the locally optimal choice at each stage. A Dynamic programming is an algorithmic technique which is usually based on a recurrent formula that uses some previously calculated states.
Memoization It is more efficient in terms of memory as it never look back or revise previous choices It requires dp table for memoization and it increases it’s memory complexity.
Time complexity Greedy methods are generally faster. For example, Dijkstra’s shortest path algorithm takes O(ELogV + VLogV) time. Dynamic Programming is generally slower. For example, Bellman Ford algorithm takes O(VE) time.
Fashion The greedy method computes its solution by making its choices in a serial forward fashion, never looking back or revising previous choices. Dynamic programming computes its solution bottom up or top down by synthesizing them from smaller optimal sub solutions.
Example Fractional knapsack . 
 
0/1 knapsack problem