File tree Expand file tree Collapse file tree 1 file changed +27
-2
lines changed
leetcode/dynamic_programming Expand file tree Collapse file tree 1 file changed +27
-2
lines changed Original file line number Diff line number Diff line change @@ -53,6 +53,8 @@ class Solution
53
53
{
54
54
public:
55
55
int uniquePaths (int m, int n);
56
+
57
+ int uniquePaths1 (int m, int n);
56
58
};
57
59
58
60
/* *
@@ -83,7 +85,7 @@ class Solution
83
85
* ├───────────────────────────│
84
86
*
85
87
* 时间复杂度: O(m × n)
86
- * 空间复杂度: O(n)
88
+ * 空间复杂度: O(m x n)
87
89
*
88
90
*/
89
91
int Solution::uniquePaths (int m, int n)
@@ -106,14 +108,37 @@ int Solution::uniquePaths(int m, int n)
106
108
return dp[m - 1 ][n - 1 ];
107
109
};
108
110
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
+
109
134
int main (int argc, char const *argv[])
110
135
{
111
136
Solution s;
112
137
int m = 3 , n = 7 ;
113
138
int m1 = 5 , n1 = 9 ;
114
139
115
140
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;
117
142
118
143
return 0 ;
119
144
}
You can’t perform that action at this time.
0 commit comments