@LIUHUAN
2020-06-30T15:25:09.000000Z
字数 1869
阅读 859
algorithm
int uniquePaths(int m, int n) { return dfs(m, n); }int dfs(int m, int n) {if (m == 1 || n == 1) {return 1;}return dfs(m - 1, n) + dfs(m, n - 1);}
map,也可以用数组,来缓存已经计算完的数据。对于已经获取的数据直接返回结果。map来保存,例如map[2-3]=3,下次计算的时候可以直接使用
unordered_map<string, int> cache;int uniquePaths(int m, int n) {return memo(m, n);return dfs(m, n);}int memo(int m, int n) {if (m == 1 || n == 1) {return 1;}auto key = getkey(m, n);if (cache.find(key) != cache.end()) {return cache[key];}auto x = memo(m - 1, n) + memo(m, n - 1);cache[key] = x;return x;}string getkey(int m, int n) {return to_string(m) + "_" + to_string(n);}
int uniquePaths(int m, int n) {return dyp(m, n);}int dyp(int m, int n) {vector<vector<int>> dp(m, vector<int>(n, 0));for (int i = 0; i < m; i++) {dp[i][0] = 1;}for (int j = 0; j < n; j++) {dp[0][j] = 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];}}return dp[m - 1][n - 1];}
int uniquePaths(int m, int n) {return dypopt(m, n);}int dypopt(int m, int n) {vector<int> pre(n, 1), cur(n, 1);for (int i = 1; i < m; i++) {for (int j = 1; j < n; j++) {cur[j] = cur[j - 1] + pre[j];}swap(pre, cur);}return pre[n - 1];}
cur[j] = cur[j] + cur[j-1]