Leetcode 62. 不同路径

 

 

 

 

 

 

 

 

 

代码:

 

 1 # include <iostream>
 2 # include <vector>
 3 using namespace std;
 4 
 5 
 6 //递归
 7 
 8 int uniquePaths1(int m, int n)
 9 {
10     if(m==1 ||n==1) return 1;
11     if(m==2 && n==2) return 2;
12     else return uniquePaths1(m-1,n)+uniquePaths1(m,n-1);
13 }
14 
15 // 动态规划
16 class Solution {
17 public:
18     int uniquePaths(int m, int n) {
19         int a[m+1][n+1];
20         int i, j;
21         for(i=1; i<=m; i++)
22         {
23             for(j=1; j<=n; j++)
24             {
25                 if(i==1 || j==1)  a[i][j] = 1;
26                 else  a[i][j] = a[i-1][j] + a[i][j-1];
27             }
28         }
29         return a[m][n];
30     }
31 };
32 
33 
34 int main()
35 {
36     int m, n;
37     cin >> m;
38     cin >> n;
39     
40     cout << "利用 递归方式 从矩阵的左上角走到右下角可能的路径有:"<< uniquePaths1(m, n) << endl;
41 
42     Solution sol;
43     cout << "利用 动态规划 从矩阵的左上角走到右下角可能的路径有:" << sol.uniquePaths(m, n) << endl;
44     system("pause");
45 }

 

posted @ 2020-10-24 22:30  wgx_wayne  阅读(69)  评论(0)    收藏  举报