ValidSudoku
问题描述
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.
分析
题目要求是检验行列以及每个小方格内的数字没有重复,那么可以使用三个哈希表分别记录这三个方面值是否已经存在,依次遍历,对于不为空值,查找哈希表,不存在则记录该值,存在即返回false。
解答
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int row[9][9] = {0};
int col[9][9] = {0};
int block[9][9] = {0};
for(int rowNumber = 0; rowNumber < board.size(); rowNumber++)
for(int colNumber = 0; colNumber < board[rowNumber].size(); colNumber++)
if(board[rowNumber][colNumber] != '.')
{
int key = board[rowNumber][colNumber] - '0' - 1;
int blNumber = rowNumber / 3 * 3 + colNumber / 3;
if(row[rowNumber][key] || col[colNumber][key] || block[blNumber][key])
return false;
row[rowNumber][key] = 1;
col[colNumber][key] = 1;
block[blNumber][key] = 1;
}
return true;
}
};
Combination Sum
问题描述
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
• All numbers (including target) will be positive integers.
• The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
分析
使用回溯算法来解决本问题,由于可以在候选数组中重复的取值,所以我们需要考虑一个值取多次的时候。先将数组排序,然后从头开始,取一个值作为备选答案其中的一个值,然后递归的进行这样的操作,将其中的target值减去已经放入备选答案的值,如果最后的target为0,那么该次递归得到的备选答案为正确的,否则为错误的。
解答
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<std::vector<int> > result;
vector<int> combination;
combinationSum(candidates, target, result, combination, 0);
return result;
}
void combinationSum(vector<int> &candidates, int target, vector<vector<int> > &res, vector<int> &combination, int begin)
{
if (!target)
{
res.push_back(combination);
return;
}
for (int i = begin; i < candidates.size() && target >= candidates[i]; i++)
{
combination.push_back(candidates[i]);
combinationSum(candidates, target - candidates[i], res, combination, i);
combination.pop_back();
}
}
};