# Unique Paths

Oct 18, 2017

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

How many possible unique paths are there? Note: m and n will be at most 100.

int uniquePaths(int m, int n) {
if (m == 1 || n == 1) return 1;
return uniquePaths(m-1,n) + uniquePaths(m,n-1);
}

int uniquePaths(int m, int n) {
int *p = new int[m*n];
for(int i = 0;i < n;i++)
p[i] = 1;
for(int j = 0;j < m;j++)
p[n*j] = 1;

for(int i = 1;i < m;i++)
for(int j = 1;j < n;j++)
p[i*n+j] = p[ (i-1)*n +j ] + p[i*n + j - 1];

return p[m*n-1];
}

int uniquePaths(int m, int n) {
vector<vector<int> > path(m, vector<int> (n, 1));
for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++)
path[i][j] = path[i - 1][j] + path[i][j - 1];
return path[m - 1][n - 1];
}

(捂脸)我一直不知道怎么用vector来快速的构造二维数组。

int uniquePaths(int m, int n) {
if (m > n) return uniquePaths(n, m);
vector<int> pre(m, 1);
vector<int> cur(m, 1);
for (int j = 1; j < n; j++) {
for (int i = 1; i < m; i++)
cur[i] = cur[i - 1] + pre[i];
swap(pre, cur);
}
return pre[m - 1];
}

int uniquePaths(int m, int n) {
if (m > n) return uniquePaths(n, m);
vector<int> cur(m, 1);
for (int j = 1; j < n; j++)
for (int i = 1; i < m; i++)
cur[i] += cur[i - 1];
return cur[m - 1];
}
LeetCodeLeetCode动态规划

Sort Colors

Merge-Intervals