记忆化和动态规划有什么区别?

发布于 2024-11-10 07:52:15 字数 40 浏览 4 评论 0原文

记忆化和动态规划有什么区别?我认为动态编程是记忆的一个子集。对吗?

What is the difference between memoization and dynamic programming? I think dynamic programming is a subset of memoization. Is it right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

演出会有结束 2024-11-17 07:52:15

记忆化和动态编程有什么区别?

记忆化是一个描述优化技术的术语,在该技术中,您可以缓存先前计算的结果,并返回缓存的结果当再次需要相同的计算时。

动态规划是一种迭代解决递归性质问题的技术,适用于子问题计算重叠的情况。

动态编程通常使用制表来实现,但也可以使用记忆来实现。正如您所看到的,两者都不是另一个的“子集”。


一个合理的后续问题是:制表(典型的动态编程技术)和记忆之间有什么区别?

当您使用制表解决动态规划问题时,您解决的是“自下而上”的问题”,即首先解决所有相关的子问题,通常是通过填充一个n维表。然后根据表中的结果计算“顶部”/原始问题的解决方案。

如果您使用记忆来解决问题,您可以通过维护已解决的子问题的映射来实现。您按照“自上而下”的方式进行操作,即首先解决“顶部”问题(通常会向下递归以解决子问题)。

一张来自此处<的精彩幻灯片/strike> (链接现已失效,但幻灯片仍然很好):

  • 如果所有子问题必须至少解决一次,则自下而上的动态规划算法通常比自上而下的记忆算法性能好一个常数因子
    • 没有递归开销,维护表的开销更少
    • 对于某些问题,可以利用动态编程算法中的常规表访问模式来进一步减少时间或空间需求
  • 如果子问题空间中的某些子问题根本不需要解决,则记忆解决方案的优点是仅解决那些肯定需要的子问题

其他资源:

What is difference between memoization and dynamic programming?

Memoization is a term describing an optimization technique where you cache previously computed results, and return the cached result when the same computation is needed again.

Dynamic programming is a technique for solving problems of recursive nature, iteratively and is applicable when the computations of the subproblems overlap.

Dynamic programming is typically implemented using tabulation, but can also be implemented using memoization. So as you can see, neither one is a "subset" of the other.


A reasonable follow-up question is: What is the difference between tabulation (the typical dynamic programming technique) and memoization?

When you solve a dynamic programming problem using tabulation you solve the problem "bottom up", i.e., by solving all related sub-problems first, typically by filling up an n-dimensional table. Based on the results in the table, the solution to the "top" / original problem is then computed.

If you use memoization to solve the problem you do it by maintaining a map of already solved sub problems. You do it "top down" in the sense that you solve the "top" problem first (which typically recurses down to solve the sub-problems).

A good slide from here (link is now dead, slide is still good though):

  • If all subproblems must be solved at least once, a bottom-up dynamic-programming algorithm usually outperforms a top-down memoized algorithm by a constant factor
    • No overhead for recursion and less overhead for maintaining table
    • There are some problems for which the regular pattern of table accesses in the dynamic-programming algorithm can be exploited to reduce the time or space requirements even further
  • If some subproblems in the subproblem space need not be solved at all, the memoized solution has the advantage of solving only those subproblems that are definitely required

Additional resources:

独留℉清风醉 2024-11-17 07:52:15

动态规划是一种解决给定问题的算法范式
通过将其分解为子问题并存储结果来解决复杂问题
子问题以避免再次计算相同的结果。

http://www.geeksforgeeks.org/dynamic-programming-set-1/

记忆化是一种跟踪先前解决的解决方案的简单方法(通常作为哈希键值对实现,而不是通常基于数组的制表),这样当再次遇到它们时就不会重新计算。它可以用于自下而上或自上而下的方法。

请参阅有关记忆化与制表的讨论

因此,动态编程是一种通过解决递归关系/递归并通过表格或记忆存储先前找到的解决方案来解决某些类别问题的方法。记忆化是一种跟踪先前解决的问题的解决方案的方法,可与对给定输入集具有唯一确定性解决方案的任何函数一起使用。

Dynamic Programming is an algorithmic paradigm that solves a given
complex problem by breaking it into subproblems and stores the results
of subproblems to avoid computing the same results again.

http://www.geeksforgeeks.org/dynamic-programming-set-1/

Memoization is an easy method to track previously solved solutions (often implemented as a hash key value pair, as opposed to tabulation which is often based on arrays) so that they aren't recalculated when they are encountered again. It can be used in both bottom up or top down methods.

See this discussion on memoization vs tabulation.

So Dynamic programming is a method to solve certain classes of problems by solving recurrence relations/recursion and storing previously found solutions via either tabulation or memoization. Memoization is a method to keep track of solutions to previously solved problems and can be used with any function that has unique deterministic solutions for a given set of inputs.

于我来说 2024-11-17 07:52:15

记忆化和动态编程都只解决单个子问题一次。

记忆化使用递归并自上而下地工作,而动态编程则相反,自下而上地解决问题。

下面是一个有趣的类比 -

自上而下 - 首先你说我将接管世界。你会怎么做?你说我先占领亚洲。你会怎么做?我将首先接管印度。我将成为德里的首席部长,等等。

自下而上 - 你说我将成为德里的首席部长。然后我将接管印度,然后是亚洲所有其他国家,最后我将接管世界。

Both Memoization and Dynamic Programming solves individual subproblem only once.

Memoization uses recursion and works top-down, whereas Dynamic programming moves in opposite direction solving the problem bottom-up.

Below is an interesting analogy -

Top-down - First you say I will take over the world. How will you do that? You say I will take over Asia first. How will you do that? I will take over India first. I will become the Chief Minister of Delhi, etc. etc.

Bottom-up - You say I will become the CM of Delhi. Then will take over India, then all other countries in Asia and finally I will take over the world.

妥活 2024-11-17 07:52:15

动态规划通常称为记忆化!

  1. 记忆化是自上而下的技术(通过分解来开始解决给定的问题),而动态编程是自下而上的技术(从琐碎的子问题开始解决,向上解决给定的问题)

  2. DP找到解决方案从基本案例开始并向上进行。
    DP 解决了所有子问题,因为它是自下而上的

    <块引用>

    与 Memoization 不同,Memoization 仅解决所需的子问题

  3. ,DP 具有将指数时间暴力解决方案转换为多项式时间算法的潜力。

  4. DP 可能会更高效,因为它是迭代的

    <块引用>

    相反,Memoization 必须支付由于递归而产生的(通常是很大的)开销。

更简单地说,
记忆化使用自上而下的方法来解决问题,即从核心(主要)问题开始,然后将其分解为子问题,并以类似的方式解决这些子问题。在这种方法中,相同的子问题可能会出现多次并消耗更多的CPU周期,从而增加时间复杂度。而在动态规划中,相同的子问题不会被多次解决,但先前的结果将用于优化解决方案。

Dynamic Programming is often called Memoization!

  1. Memoization is the top-down technique(start solving the given problem by breaking it down) and dynamic programming is a bottom-up technique(start solving from the trivial sub-problem, up towards the given problem)

  2. DP finds the solution by starting from the base case(s) and works its way upwards.
    DP solves all the sub-problems, because it does it bottom-up

    Unlike Memoization, which solves only the needed sub-problems

  3. DP has the potential to transform exponential-time brute-force solutions into polynomial-time algorithms.

  4. DP may be much more efficient because its iterative

    On the contrary, Memoization must pay for the (often significant) overhead due to recursion.

To be more simple,
Memoization uses the top-down approach to solve the problem i.e. it begin with core(main) problem then breaks it into sub-problems and solve these sub-problems similarly. In this approach same sub-problem can occur multiple times and consume more CPU cycle, hence increase the time complexity. Whereas in Dynamic programming same sub-problem will not be solved multiple times but the prior result will be used to optimize the solution.

幽蝶幻影 2024-11-17 07:52:15

(1) 记忆化和DP,在概念上,实际上是同一件事。因为:考虑DP的定义:“重叠子问题”“和最优子结构”。 Memoization完全具备这2个。

(2) Memoization是DP,由于递归很深,存在堆栈溢出的风险。 DP自下而上不存在这种风险。

(3) Memoization需要哈希表。因此需要额外的空间和一些查找时间。

所以回答这个问题:

-概念上,(1) 意味着它们是同一件事。

-考虑到(2),如果你真的想要,memoization是DP的子集,从某种意义上说,可以通过memoization解决的问题也可以通过DP解决,但是可以通过DP解决的问题可能无法通过memoization解决(因为它可能堆栈溢出)。

-考虑到(3),它们在性能上有微小差异。

(1) Memoization and DP, conceptually, is really the same thing. Because: consider the definition of DP: "overlapping subproblems" "and optimal substructure". Memoization fully possesses these 2.

(2) Memoization is DP with the risk of stack overflow is the recursion is deep. DP bottom up does not have this risk.

(3) Memoization needs a hash table. So additional space, and some lookup time.

So to answer the question:

-Conceptually, (1) means they are the same thing.

-Taking (2) into account, if you really want, memoization is a subset of DP, in a sense that a problem solvable by memoization will be solvable by DP, but a problem solvable by DP might not be solvable by memoization (because it might stack overflow).

-Taking (3) into account, they have minor differences in performance.

糖粟与秋泊 2024-11-17 07:52:15

来自维基百科:

记忆化

在计算中,记忆化是一种主要使用的优化技术
通过函数调用避免重复来加速计算机程序
计算先前处理的输入的结果。

动态规划

在数学和计算机科学中,动态规划是一种方法
通过将复杂的问题分解为更简单的问题来解决它们
子问题。

当将问题分解为更小/更简单的子问题时,我们经常会多次遇到相同的子问题 - 因此我们使用记忆化来保存先前计算的结果,这样我们就不需要重复它们。

动态编程经常遇到使用记忆化有意义的情况,但您可以使用其中一种技术而不必使用另一种技术。

From wikipedia:

Memoization

In computing, memoization is an optimization technique used primarily
to speed up computer programs by having function calls avoid repeating
the calculation of results for previously-processed inputs.

Dynamic Programming

In mathematics and computer science, dynamic programming is a method
for solving complex problems by breaking them down into simpler
subproblems.

When breaking a problem into smaller/simpler subproblems, we often encounter the same subproblem more then once - so we use Memoization to save results of previous calculations so we don't need to repeat them.

Dynamic programming often encounters situations where it makes sense to use memoization but You can use either technique without necessarily using the other.

温柔一刀 2024-11-17 07:52:15

我想看一个示例

问题:

您正在爬楼梯。需要n步才能到达顶部。

每次您可以爬 1 或 2 级台阶。有多少种不同的方式
你能爬到山顶吗?

输入图像描述这里

带有记忆化的递归

通过这种方式,我们可以借助 memo 数组来修剪(从树木或灌木中去除多余的材料)递归树并减少递归的大小树直到 nn。

public class Solution {
    public int climbStairs(int n) {
        int memo[] = new int[n + 1];
        return climb_Stairs(0, n, memo);
    }
    public int climb_Stairs(int i, int n, int memo[]) {
        if (i > n) {
            return 0;
        }
        if (i == n) {
            return 1;
        }
        if (memo[i] > 0) {
            return memo[i];
        }
        memo[i] = climb_Stairs(i + 1, n, memo) + climb_Stairs(i + 2, n, memo);
        return memo[i];
    }
}

动态规划

我们可以看到这个问题可以分解为子问题,并且它包含最优子结构性质,即它的最优解可以从子问题的最优解中高效地构造出来,我们可以使用动态规划来解决这个问题。

public class Solution {
    public int climbStairs(int n) {
        if (n == 1) {
            return 1;
        }
        int[] dp = new int[n + 1];
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }
}

示例取自https://leetcode.com/problems/climbing-stairs/

I would like to go with an example;

Problem:

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways
can you climb to the top?

enter image description here

Recursion with Memoization

In this way we are pruning (a removal of excess material from a tree or shrub) recursion tree with the help of memo array and reducing the size of recursion tree upto nn.

public class Solution {
    public int climbStairs(int n) {
        int memo[] = new int[n + 1];
        return climb_Stairs(0, n, memo);
    }
    public int climb_Stairs(int i, int n, int memo[]) {
        if (i > n) {
            return 0;
        }
        if (i == n) {
            return 1;
        }
        if (memo[i] > 0) {
            return memo[i];
        }
        memo[i] = climb_Stairs(i + 1, n, memo) + climb_Stairs(i + 2, n, memo);
        return memo[i];
    }
}

Dynamic Programming

As we can see this problem can be broken into subproblems, and it contains the optimal substructure property i.e. its optimal solution can be constructed efficiently from optimal solutions of its subproblems, we can use dynamic programming to solve this problem.

public class Solution {
    public int climbStairs(int n) {
        if (n == 1) {
            return 1;
        }
        int[] dp = new int[n + 1];
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }
}

Examples take from https://leetcode.com/problems/climbing-stairs/

初懵 2024-11-17 07:52:15

只要想到两种方法,

  1. 我们将更大的问题分解为更小的子问题 - 自上而下的方法。
  2. 我们从最小的子问题开始,到达更大的问题——自下而上的方法。

记忆化中,我们采用 (1.) 将每个函数调用保存在缓存中并从那里回调。它有点昂贵,因为它涉及递归调用。

动态编程中,我们采用 (2.) 方式维护一个表,通过使用表(通常称为 dp 表)中保存的数据解决子问题,自下而上。

注意:

  • 两者都适用于具有重叠子问题的问题。

  • 由于递归函数调用期间涉及的开销,Memoization 的性能相对较差。

  • 渐近时间复杂度保持不变。

Just think of two ways,

  1. We break down the bigger problem into smaller sub problems - Top down approach.
  2. We start from smallest sub problem and reach the bigger problem - Bottom up approach.

In Memoization we go with (1.) where we save each function call in a cache and call back from there. Its a bit expensive as it involves recursive calls.

In Dynamic Programming we go with (2.) where we maintain a table, bottom up by solving subproblems using the data saved in the table, commonly referred as the dp-table.

Note:

  • Both are applicable to problems with Overlapping sub-problems.

  • Memoization performs comparatively poor to DP due to the overheads involved during recursive function calls.

  • The asymptotic time-complexity remains the same.
淡淡離愁欲言轉身 2024-11-17 07:52:15

动态编程 (DP) 和记忆化之间有一些相似之处,在大多数情况下,您可以通过记忆化来实现动态编程过程,反之亦然。但它们确实有一些差异,您应该在决定使用哪种方法时检查它们:

  • 记忆化是一种自上而下的方法,在此过程中,您将一个大问题分解为具有相同属性的较小尺寸的子问题,并且当尺寸足够小时,您可以通过暴力破解轻松解决它。 动态规划是一种自下而上的方法,首先计算小案例的答案,然后用它们来构造大案例的答案。
  • 在编码过程中,记忆通常是通过递归来实现的,而动态规划则是通过迭代来实现计算的。因此,如果您仔细计算了算法的空间和时间复杂度,那么使用动态编程风格的实现可以为您提供更好的性能。
  • 确实存在使用记忆具有优势的情况。动态规划需要计算每一个子问题,因为它不知道哪个子问题将来有用。但记忆化仅计算与原始问题相关的子问题。有时你可能会设计一个理论上具有大量 dp 状态的 DP 算法。但通过仔细分析,您会发现只有可接受的数量才会被使用。在这种情况下,最好使用记忆来避免大量的执行时间。

There're some similarities between dynamic programming (DP) and memoization and in most cases you can implement a dynamic programming process by memoization and vise versa. But they do have some differences and you should check them out when deciding which approach to use:

  • Memoization is a top-down approach during which you decompose a big problem into smaller-size subproblems with the same properties and when the size is small enough you can easily solve it by bruteforcing. Dynamic Programming is a bottom-up approach during which you firstly calculate the answer of small cases and then use them to construct the answer of big cases.
  • During coding, usually memoization is implemented by recursion while dynamic programming does calculation by iteration. So if you have carefully calculate the space and time complexity of your algorithm, using dynamic-programming-style implementation can offer you better performance.
  • There do exist situations where using memoization has advantages. Dynamic programming needs to calculate every subproblem because it doesn't know which one will be useful in the future. But memoization only calculate the subproblems related to the original problem. Sometimes you may design a DP algorithm with theoretically tremendous amount of dp status. But by careful analyses you find that only an acceptable amount of them will be used. In this situation it's preferred to use memoization to avoid huge execution time.
暮凉 2024-11-17 07:52:15

动态编程中,

  • 没有递归开销,维护表的开销更少。
  • 表访问的规则模式可用于减少时间或空间需求。

记忆中,

  • 有些子问题是不需要解决的。

In Dynamic Programming ,

  • No overhead for recursion, less overhead for maintaining the table.
  • The regular pattern of the table accesses may be used to reduce time or space requirements.

In Memorization,

  • Some subproblems do not need to be solved.
眼角的笑意。 2024-11-17 07:52:15

以下是用 Java 编写的斐波那契数问题的记忆化和 DP 示例。

这里的动态编程不涉及递归,因为它不受执行堆栈的限制,结果更快并且可以计算更高的值。

public class Solution {

 public static long fibonacciMemoization(int i) {
    return fibonacciMemoization(i, new long[i + 1]);
 }

 public static long fibonacciMemoization(int i, long[] memo) {
    if (i <= 1) {
        return 1;
    }
    if (memo[i] != 0) {
        return memo[i];
    }
    long val = fibonacciMemoization(i - 1, memo) + fibonacciMemoization(i - 2, memo);
    memo[i] = val;
    return val;
 }

 public static long fibonacciDynamicPrograming(int i) {
    if (i <= 1) {
        return i;
    }
    long[] memo = new long[i + 1];
    memo[0] = 1;
    memo[1] = 1;
    memo[2] = 2;
    for (int j = 3; j <= i; j++) {
        memo[j] = memo[j - 1] + memo[j - 2];
    }
    return memo[i];
 }

 public static void main(String[] args) {
    System.out.println("Fibonacci with Dynamic Programing");
    System.out.println(fibonacciDynamicPrograming(10));
    System.out.println(fibonacciDynamicPrograming(1_000_000));

    System.out.println("Fibonacci with Memoization");
    System.out.println(fibonacciMemoization(10));
    System.out.println(fibonacciMemoization(1_000_000)); //stackoverflow exception
 }
}

Here is a sample of Memoization and DP from Fibonacci Number problem written in Java.

Dynamic Programming here is not involving the recursion, as result faster and can calculate higher values because it is not limited by the execution stack.

public class Solution {

 public static long fibonacciMemoization(int i) {
    return fibonacciMemoization(i, new long[i + 1]);
 }

 public static long fibonacciMemoization(int i, long[] memo) {
    if (i <= 1) {
        return 1;
    }
    if (memo[i] != 0) {
        return memo[i];
    }
    long val = fibonacciMemoization(i - 1, memo) + fibonacciMemoization(i - 2, memo);
    memo[i] = val;
    return val;
 }

 public static long fibonacciDynamicPrograming(int i) {
    if (i <= 1) {
        return i;
    }
    long[] memo = new long[i + 1];
    memo[0] = 1;
    memo[1] = 1;
    memo[2] = 2;
    for (int j = 3; j <= i; j++) {
        memo[j] = memo[j - 1] + memo[j - 2];
    }
    return memo[i];
 }

 public static void main(String[] args) {
    System.out.println("Fibonacci with Dynamic Programing");
    System.out.println(fibonacciDynamicPrograming(10));
    System.out.println(fibonacciDynamicPrograming(1_000_000));

    System.out.println("Fibonacci with Memoization");
    System.out.println(fibonacciMemoization(10));
    System.out.println(fibonacciMemoization(1_000_000)); //stackoverflow exception
 }
}
も星光 2024-11-17 07:52:15

动态编程是对普通递归算法的优化,它考虑输入的所有组合以提供最合适的答案。这种方法有一个缺点,即时间复杂度巨大。通过使用记忆可以提高效率。它将存储子问题的每个输出,并在算法尝试再次解决该子问题时直接给出答案。这可以使算法具有多项式时间复杂度。

Dynamic Programming is an optimization over plain recursive algorithm which consider all the combination of the input to provide the most suitable answer. This approach has one drawback, its huge time complexity. It can be made more efficient by the use of memoization. It will store every output of a subproblem and will directly give an answer, whenever that algorithm tries to solve that subproblem again. This can make the algorithm have polynomial time complexity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文