很遗憾,第一遍又没做出来。。大概原因,确实还是没想到可以通过多次循环以及四个for循环来解决四条边的问题,而且C++的掌握也不够熟练,不熟悉VECTOR嵌套VECTOR二维数组的使用。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n,0));
int loop = n / 2;
int i = 0, j = 0;
int count = 1;
int startx = 0, starty = 0;
int offset = 1;
while (loop-- > 0){
for (i = startx,j = starty; j < n - offset; j++){
res[i][j] = count++;
}
for (; i < n - offset; i++){
res[i][j] = count++;
}
for (; j > starty; j--){
res[i][j] = count++;
}
for (; i > startx; i--){
res[i][j] = count++;
}
startx += 1;
starty += 1;
offset += 1;
}
if (n % 2){
res[n/2][n/2] = count;
}
return res;
}
};
这样看来,有时按照正向思维去实现问题也不失为是一种思路。