나는 leetcode 문제를 해결하고 있습니다.재귀 알고리즘의 두 가지 구현의 차이점은 무엇입니까?
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
그래서이 구현을 먼저 시도하고 "런타임 초과"(정확한 용어는 잊어 버렸지 만 구현이 느리다는 의미입니다). 그래서 배열을 사용하여 결과를 저장하는 버전 2를 변경했습니다. 솔직히 재귀가 내부적으로 어떻게 작동하는지, 왜이 두 구현이 다른 효율성을 갖는지에 대해서는 알지 못합니다.
버전 1 (저속) :
class Solution {
// int res[101][101]={{0}};
public:
int uniquePaths(int m, int n) {
if (m==1 || n==1) return 1;
else{
return uniquePaths(m-1,n) + uniquePaths(m,n-1);
}
}
};
버전 2 (빠르게) :
class Solution {
int res[101][101]={{0}};
public:
int uniquePaths(int m, int n) {
if (m==1 || n==1) return 1;
else{
if (res[m-1][n]==0) res[m-1][n] = uniquePaths(m-1,n);
if (res[m][n-1]==0) res[m][n-1] = uniquePaths(m,n-1);
return res[m-1][n] + res[m][n-1];
}
}
};
초반부는 초당 https://en.wikipedia.org 인 것 같습니다./wiki/Dynamic_programming. 결과를 두 번 계산하지 않습니다. 두 메소드의 시작 부분에'System.out.println ("+ m +"및 "+ n"으로 호출)을 추가하고 작은 입력으로 시도하십시오. 차이점을 확인할 수 있습니다. 또한 참조 http://stackoverflow.com/a/25665931/3182664 – Marco13
그것은 메모를 사용합니다 – Sylwester