Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
解析: 就是每行每列1~9出现且只出现一次,另外每个大正方形中,也是1~9出现且仅出现一次,这里限定了布局。
这里是判断,不是让你填,一开始考虑填数去了,这里只考虑是否可以满足上面条件(即使没填满),所以思路是每行每列的看,如果1~9有某个数重复出现过,则不满足,再考虑大方框中的情况。另外人家说了,表格可以是未填满的,未填满的也算valid,所以考虑把'.'考虑进去就行了。
class Solution {
public:
bool check(char ch,bool used[9])
{
if ('.' == ch) return true; //可
if (used[ch - '1']) return false; //如果其已经被置true,证明被用过
used[ch - '1'] = true; //置true
return true;
}
bool isValidSudoku(vector<vector<char> > &board) {
bool used[9];
for (int i = 0; i < 9 ; ++i)
{
fill(used,used + 9,false); //初始,检查行
for (int j = 0; j < 9; ++j)
if (!check(board[i][j],used))
return false;
fill(used,used + 9,false);
for (int j = 0; j < 9; ++j) //检查列,别忘了检查前初始化
if (!check(board[j][i],used))
return false;
}
for(int r = 0; r < 3; ++r) //检查九个大方框
for (int c = 0; c < 3; ++c)
{
fill(used,used + 9, false);
for (int i = 3*r; i < 3*r + 3; ++i) //注意其表示
for(int j = 3*c; j < 3*c + 3; ++j)
if (!check(board[i][j],used))
return false;
}
return true;
}
};
2.
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
3.
Rotate Image
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
解析: 这题知道思路后就比较简单,旋转90度,先对角线交换后水平线上下交换,即可,用std::swap其函数实现比较高校,能in_place
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
const int n = matrix.size();
for (int i = 0; i < n; ++i) //对角线交换
for (int j = 0; j < n- i; ++j)
swap(matrix[i][j],matrix[n - 1 - j][n - 1 - i]);
for (int i = 0; i < n/2; ++i) //上下交换
for (int j = 0; j < n; ++j)
swap(matrix[i][j],matrix[n - 1 - i][j]);
}
};
4.
Plus One
The digits are stored such that the most significant digit is at the head of the list.
解析:一开始看不明白,这是干啥的,原来是数字可能超出其常规数据类型范围,所以改用数组存储。这里的答案还是比较通用的。
class Solution {
public:
void add(vector<int>& digits, int digit)
{
int carry = digit;
for (auto it = digits.rbegin();it != digits.rend(); ++it)
{
*it += carry;
carry = *it/10;
*it %= 10;
}
if (carry > 0 ) digits.insert(digits.begin(),1);
}
vector<int> plusOne(vector<int> &digits) {
add(digits,1);
return digits;
}
};
5.
Climbing Stairs
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?class Solution {
解析: 这题只要 知道这是一个f(n) = f(n-1) + f(n - 2);的描述就简单了
public:
int climbStairs(int n) {
int pre = 0;
int cur = 1;
for (int i = 0; i < n ; ++i)
{
int temp = cur;
cur = pre + cur;
pre = temp;
}
return cur;
}
};