📜  贪婪方法与动态编程

📅  最后修改于: 2021-09-11 03:44:13             🧑  作者: 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 
 

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。