题目描述
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish” )。
现在考虑网格中有障碍物。问总共有多少条不同的路径?
思路
代码
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int n = obstacleGrid.size(), m = obstacleGrid.at(0).size();
vector <int> f(m);
f[0] = (obstacleGrid[0][0] == 0);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (obstacleGrid[i][j] == 1) {
f[j] = 0;
continue;
}
if (j - 1 >= 0 && obstacleGrid[i][j - 1] == 0) {
f[j] += f[j - 1];
}
}
}
return f.back();
//return f[m-1];
}
};
vector<int> split(string params_str) {
vector<int> p;
while (params_str.find(",") != string::npos) {
int found = params_str.find(",");
p.push_back(stoi(params_str.substr(0, found)));
params_str = params_str.substr(found + 1);
}
p.push_back(stoi(params_str));
return p;
}
vector<vector<int>> v;
vector<int> p;
vector<vector<int>> split_2_dimention(string s) {
s += " ";//防止最后一个]后面没有元素所导致的越界
while (s.find("]") != string::npos) {
int found_right = s.find("]");
string s1 = s.substr(1, found_right - 1);
p = split(s1);
v.push_back(p);
s = s.substr(found_right + 2);//取第二个vector,这里可能会越界
p.clear();
}
return v;
}
int main() {
string input;
getline(cin, input);//[[0,0,0],[0,1,0],[0,0,0]]
string input_str = input.substr(1, input.size() - 2);
vector<vector<int>> dp;
dp = split_2_dimention(input_str);
Solution a;
cout << a.uniquePathsWithObstacles(dp);
}
复杂度分析
时间复杂度:O(nm),其中 n 为网格的行数,m 为网格的列数。我们只需要遍历所有网格一次即可。
空间复杂度:O(m)。利用滚动数组优化,我们可以只用 O(m) 大小的空间来记录当前行的 f 值。