Algorithm/dp
[알고리즘] 리트코드 고유경로 c++ // dp 모든유형
Mini_96
2024. 7. 1. 11:43
https://leetcode.com/problems/unique-paths/description/
* 완탐
class Solution {
public:
int uniquePaths(int m, int n, int i = 0, int j = 0) {
if(i >= m || j >= n) return 0; // reached out of bounds - invalid
if(i == m-1 && j == n-1) return 1; // reached the destination - valid solution
return uniquePaths(m, n, i+1, j) + uniquePaths(m, n, i, j+1); // try both down and right
}
};
* 재귀 dp
class Solution {
public:
int dp[101][101]{};
int uniquePaths(int m, int n, int i = 0, int j = 0) {
if(i >= m || j >= n) return 0;
if(i == m-1 && j == n-1) return 1;
if(dp[i][j]) return dp[i][j];
return dp[i][j] = uniquePaths(m, n, i+1, j) + uniquePaths(m, n, i, j+1);
}
};
*표 dp
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector<int>(n, 1));
for(int i = 1; i < m; i++)
for(int j = 1; j < n; j++)
dp[i][j] = dp[i-1][j] + dp[i][j-1]; // sum of unique paths ending at adjacent top and left cells
return dp[m-1][n-1]; // return unique paths ending at cell (m-1, n-1)
}
};
* 표 dp && 공간최적화
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> dp(n, 1);
for(int i = 1; i < m; i++)
for(int j = 1; j < n; j++)
dp[j] += dp[j-1];
return dp[n-1];
}
};