Skip to content

Commit a2024c8

Browse files
committed
feat: update unique paths solution
1 parent cef8174 commit a2024c8

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

leetcode/dynamic_programming/unique_paths.cpp

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ class Solution
5353
{
5454
public:
5555
int uniquePaths(int m, int n);
56+
57+
int uniquePaths1(int m, int n);
5658
};
5759

5860
/**
@@ -83,7 +85,7 @@ class Solution
8385
* ├───────────────────────────│
8486
*
8587
* 时间复杂度: O(m × n)
86-
* 空间复杂度: O(n)
88+
* 空间复杂度: O(m x n)
8789
*
8890
*/
8991
int Solution::uniquePaths(int m, int n)
@@ -106,14 +108,37 @@ int Solution::uniquePaths(int m, int n)
106108
return dp[m - 1][n - 1];
107109
};
108110

111+
/**
112+
* 可以用一位数组进行优化,类似滚动数组的方式
113+
* 时间复杂度: O(m × n)
114+
* 空间复杂度: O(n)
115+
*/
116+
int Solution::uniquePaths1(int m, int n)
117+
{
118+
vector<int> dp(n);
119+
120+
for (int i = 0; i < m; i++)
121+
dp[i] = 1;
122+
123+
for (int j = 1; j < m; j++)
124+
{
125+
for (int i = 1; i < n; i++)
126+
{
127+
dp[i] += dp[i - 1];
128+
}
129+
}
130+
131+
return dp[n - 1];
132+
};
133+
109134
int main(int argc, char const *argv[])
110135
{
111136
Solution s;
112137
int m = 3, n = 7;
113138
int m1 = 5, n1 = 9;
114139

115140
cout << "Result is: " << s.uniquePaths(m, n) << endl;
116-
cout << "Result is: " << s.uniquePaths(m1, n1) << endl;
141+
cout << "Result is: " << s.uniquePaths1(m1, n1) << endl;
117142

118143
return 0;
119144
}

0 commit comments

Comments
 (0)