Skip to content

Commit e12f22e

Browse files
authored
Merge pull request OpenGenus#6610 from Princeton21/dp
Added Unique Paths DP problem solution
2 parents 9870b8d + 3aa9895 commit e12f22e

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// Part of Cosmos by OpenGenus Foundation
2+
3+
#include<bits/stdc++.h>
4+
using namespace std;
5+
6+
7+
//Tabulation method
8+
// Time complexity: O(m*n)
9+
int uniquePaths(int m, int n) {
10+
int dp[m][n];
11+
for(int i=0;i<m;i++){
12+
for(int j=0;j<n;j++){
13+
if(i==0 || j==0)
14+
dp[i][j]=1;
15+
else
16+
dp[i][j]=dp[i-1][j]+dp[i][j-1];
17+
}
18+
}
19+
return dp[m-1][n-1];
20+
}
21+
22+
23+
//nCr method
24+
// Time complexity: O(m+n)
25+
int uniquePaths1(int m, int n) {
26+
int N=m+n-2;
27+
int r=m-1;
28+
double res=1;
29+
for(int i=1;i<=r;i++){
30+
res=res*(N-r+i)/i;
31+
}
32+
return (int)res;
33+
}
34+
35+
36+
// Brute force recursive method
37+
// Time complexity: O(2^(m+n))
38+
int uniquePaths2(int m, int n) {
39+
if(m==1 || n==1)
40+
return 1;
41+
return uniquePaths2(m-1,n)+uniquePaths2(m,n-1);
42+
}
43+
44+
//Time complexity: O(m*n)
45+
int solve(int i, int j, vector<vector<int>> &dp, int &m, int &n){
46+
if (i == m - 1 || j == n - 1) return 1;
47+
if (dp[i][j] != 0) return dp[i][j];
48+
dp[i][j] = solve(i + 1, j, dp, m, n) + solve(i, j + 1, dp, m, n);
49+
return dp[i][j];
50+
}
51+
int uniquePaths3(int m, int n){
52+
vector<vector<int>> dp(m, vector<int>(n, 0));
53+
return solve(0, 0, dp, m, n);
54+
}
55+
56+
int main(){
57+
int m,n;
58+
cin>>m>>n;
59+
cout<<uniquePaths(m,n)<< endl;
60+
cout<<uniquePaths1(m,n) << endl;
61+
cout<<uniquePaths2(m,n) << endl;
62+
cout<<uniquePaths3(m,n) << endl;
63+
return 0;
64+
}
65+

0 commit comments

Comments
 (0)