目录
学习:代码随想录
题源:LeetCode
抽象
n叉树,横轴for循环,纵轴递归
模板
// step1
type* path;
int pathTop;
type** ans;
int ansTop;void backtracing(paras){
// step2
if(条件){
tmp拷贝path;
tmp写入ans作为一个结果;
return;
}// step3
for(横轴){
// 压栈;
// 递归;
// 出栈/回溯;
}
}
type** main(){
path,ans->malloc;
pathTop = ansTop = 0;
backtracing(paras);
// 说明*returnSize和returnColSize;
}
空间大小一般<=100
【去重】树层去重+树枝去重(横向+纵向)
结果重复是由于同值元素重复使用
先对数组快排/qsort,使同值元素挨着
树层去重-->main e.g. nums = [1, 1, 3, 5] target = 4,避免1+3中1重复,nums[i]!=nums[i-1]保证
for循环中加条件:
if(i>0 && nums[i]==nums[i-1] && visited[i-1] == 0)continue;
或
if(i>startIndex && nums[i]==nums[i-1])continue; // 不使用visited[]
树枝去重-->startIndex保证
for(int i = startIndex; i<size; i++){
// 树层去重
// push
dfs(paras, i+1); // 递归-->树枝去重
// pop
}
Q.
组合
startindex相当于保证前面遍历过的不再遍历以及确定当前开始位置
例题77-组合 mid
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
示例 1:
输入:n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
int** ans;
int* path;
int anstop, pathtop;
void backtracing(int n, int k, int startIndex){
if(pathtop == k){
int* tmp = malloc(k*sizeof(int));
memcpy(tmp, path, k*sizeof(int));
ans[anstop++] = tmp;
return;
}
for(int i = startIndex; i<=n-(k-pathtop)+1; i++){ // n-当前还需节点数+1 剪枝
path[pathtop++] = i;
backtracing(n, k, i+1);
pathtop--;
}
}
int** combine(int n, int k, int* returnSize, int** returnColumnSizes) {
int ansnum = 200000;
ans = malloc(ansnum*sizeof(int*));
path = malloc(k*sizeof(int));
anstop = 0, pathtop = 0;
backtracing(n, k, 1);
*returnSize = anstop;
*returnColumnSizes = malloc(sizeof(int)*anstop);
for(int i = 0; i<anstop; i++){
(*returnColumnSizes)[i] = k;
}
return ans;
}
例题216-组合总和Ⅲ mid
找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:
- 只使用数字1到9
- 每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
示例 1:
输入: k = 3, n = 7 输出: [[1,2,4]] 解释: 1 + 2 + 4 = 7 没有其他符合的组合了。
int** ans;
int* path;
int anstop, pathtop;
int sum;
void dfs(int start, int n, int k){
if(sum == n && pathtop == k){
int* tmp = malloc(sizeof(int)*pathtop);
memcpy(tmp, path, sizeof(int)*pathtop);
ans[anstop++] = tmp;
return;
}
for(int i = start; i<=9-(k-pathtop)+1; i++){
path[pathtop++] = i;
sum += i;
if(sum > n || sum < n && pathtop == k)goto nxt;
dfs(i+1, n, k);
nxt:
pathtop--;
sum -= i;
}
}
int** combinationSum3(int k, int n, int* returnSize, int** returnColumnSizes) {
ans = malloc(sizeof(int*)*100);
path = malloc(sizeof(int)*k);
anstop = 0, pathtop = 0, sum = 0;
dfs(1, n, k);
*returnSize = anstop;
*returnColumnSizes = malloc(sizeof(int)*anstop);
for(int i = 0; i<anstop; i++){
(*returnColumnSizes)[i] = k;
}
return ans;
}
例题17-电话号码组合 mid
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
、
示例 1:
输入:digits = "23" 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
step1--> 本题返回char**
初始化char** ans记录所有可能,char* path接收某个树枝得到的结果,栈顶均为top = 0
step2--> 回溯函数边界判断
当按到最后一个数字(即index = strlen(digits)),ans记录path内容
step3--> 回溯函数体
for循环,横向看树结构,每次枚举的是第index个按键中字符之一,所以for循环遍历这组字符
// push
// dfs 树枝向下是下一个按键,故index++
// pop
// step1
char* path;
int pathTop;
char** ans;
int ansTop;
char map[11][5] = {"\0", "\0", "abc\0", "def\0", "ghi\0", "jkl\0", "mno\0", "pqrs\0", "tuv\0", "wxyz\0"};
void backtracing(char* digits, int index){
// step2
int k = strlen(digits);
if(index == k){
path[pathTop] = 0;
char* temp = malloc(sizeof(char)*(pathTop+1));
memcpy(temp, path, sizeof(char)*(pathTop+1));
ans[ansTop++] = temp;
return;
}
// step3
int digit = digits[index] - '0';
char* s = map[digit];
for(int i = 0; i<strlen(s); i++){
path[pathTop++] = s[i]; // push
backtracing(digits, index+1); // dfs
pathTop--; // pop
}
}
char** letterCombinations(char* digits, int* returnSize) {
int len = strlen(digits);
path = malloc(sizeof(char)*(len+1));
int ansSize = 1;
for(int i = 0; i<len; i++){
int index = digits[i] - '0';
if(index == 7 || index == 9)ansSize*=4;
else ansSize*=3;
} // 计算ansSize
ans = malloc(sizeof(char*)*ansSize);
ansTop = pathTop = 0;
backtracing(digits, 0);
*returnSize = ansSize;
return ans;
}
例题39-组合总和 mid
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例 1:
输入:candidates = [2,3,6,7], target = 7 输出:[[2,2,3],[7]] 解释: 2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。 7 也是一个候选, 7 = 7 。 仅有这两种组合。
int** ans;
int* path;
int anstop, pathtop;
int sum;
void dfs(int* candidates, int candidatesSize, int target, int start, int** returnColumnSizes){
if(sum == target){
int* tmp = malloc(sizeof(int)*pathtop);
memcpy(tmp, path, sizeof(int)*pathtop);
(*returnColumnSizes)[anstop] = pathtop;
ans[anstop++] = tmp;
return;
}
for(int i = start; i<candidatesSize; i++){
path[pathtop++] = candidates[i];
sum += candidates[i];
if(sum > target)goto nxt;
dfs(candidates, candidatesSize, target, i, returnColumnSizes);
nxt:
pathtop--;
sum -= candidates[i];
}
}
int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes) {
ans = malloc(sizeof(int*)*150);
*returnColumnSizes = malloc(sizeof(int)*150);
path = malloc(sizeof(int)*target);
anstop = 0, pathtop = 0, sum = 0;
dfs(candidates, candidatesSize, target, 0, returnColumnSizes);
*returnSize = anstop;
return ans;
}
例题40-组合总和 Ⅱ mid
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8 输出: [ [1,1,6], [1,2,5], [1,7], [2,6] ]
// step1
int* path;
int pathTop;
int** ans;
int ansTop;
int* anscol;
int sum = 0;
int cmp(const void* a, const void* b){
return *(int*)a - *(int*)b;
}
void backtracing(int* candidates, int n, int target, int stratIndex){
// step2
if(sum == target){
int* tmp = calloc(pathTop, sizeof(int));
memcpy(tmp, path, sizeof(int)*pathTop);
anscol[ansTop] = pathTop;
ans[ansTop++] = tmp;
return;
}
// step3
for(int i = startIndex; i<n; i++){
// key ############
if(i>startIndex && candidates[i] == candidates[i-1])continue;
path[pathTop++] = candidates[i]; // push
sum+=candidates[i];
if(sum>target){
goto nxt;
}
backtracing(candidates, n, target, i+1); // dfs
nxt:
pathTop--; // pop
sum-=candidates[i];
}
}
int** combinationSum2(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes) {
path = malloc(sizeof(int)*100);
ans = malloc(sizeof(int)*2001);
anscol = malloc(sizeof(int)*2001);
pathTop = ansTop = 0;
qsort(candidates, candidatesSize, sizeof(int), cmp);
backtracing(candidates, candidatesSize, target, 0);
*returnSize = ansTop;
*returnColumnSizes = anscol;
return ans;
}
切割
将切割位置看作组合问题,并定位字串起始和结束位
[ l, r ]型讨论,tmp存放时长度为 ( r-l+1 ) + 1 = r-l+2
即左边界可取到-->dfs后i+1(i为本次回文串最后一个元素位置)
右边界能取到-->右指针指向的是本次回文串最后一个元素位置
例题131-切割回文串 mid
给你一个字符串 s,请你将 s 分割成一些 子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
示例 1:
输入:s = "aab" 输出:[["a","a","b"],["aa","b"]]
// step1-define paras
char** path;
int pathTop;
char*** ans;
int ansTop;
int* anscnt;
// 双指针判断回文
bool isPali(char* s, int left, int right){
for(int i = left, j = right; i<j; i++,j--){
if(s[i]!=s[j])return false;
}
return true;
}
// 回溯
void backtracing(char* s, int startIndex){
// step2-收集条件
if(startIndex == strlen(s)){
path[pathTop] = '\0';
anscnt[ansTop] = pathTop;
char** tmp = malloc(sizeof(char*)*(pathTop+1));
memcpy(tmp, path, sizeof(char*)*(pathTop+1));
ans[ansTop++] = tmp;
return;
}
// step3-回溯体
for(int i = startIndex; i<strlen(s); i++){
char* t = malloc(sizeof(char)*(i-startIndex+2));
memcpy(t, s+startIndex, sizeof(char)*(i-startIndex+1));
t[i-startIndex+1] = '\0';
if(isPali(t, 0, strlen(t)-1)){
path[pathTop++] = t; // push
}else continue;
backtracing(s, i+1); // dfs
pathTop--; // pop
}
}
char*** partition(char* s, int* returnSize, int** returnColumnSizes) {
// init
int len = strlen(s)+1;
path = malloc(sizeof(char*)*len);
ans = malloc(sizeof(char**)*64*1024);
anscnt = malloc(sizeof(int)*64*1024);
ansTop = pathTop = 0;
//回溯
backtracing(s, 0);
//结果输出
*returnSize = ansTop;
*returnColumnSizes = anscnt;
return ans;
}
例题93-复原IP地址 mid
有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。
- 例如:
"0.1.2.201"和"192.168.1.1"是 有效 IP 地址,但是"0.011.255.245"、"192.168.1.312"和"192.168@1.1"是 无效 IP 地址。
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。
示例 1:
输入:s = "25525511135" 输出:["255.255.11.135","255.255.111.35"]
// way1 超过18%
bool checkValid(char* s){
int x = atoi(s);
if(strlen(s)>1 && s[0] == '0' || x>255 || x<0)return false;
return true;
}
char** trans(int** arr, int m, int n){
char** ans = malloc(sizeof(char*)*m);
for(int i = 0; i<m; i++){
ans[i] = malloc(sizeof(char)*(24));
sprintf(ans[i], "%d.%d.%d.%d", arr[i][0], arr[i][1], arr[i][2], arr[i][3]);
}
return ans;
}
int** ans;
int* path;
int anstop, pathtop;
void dfs(char* s, int n, int st){
if(pathtop == 4 && st == n){
int* tmp = malloc(sizeof(int)*4);
memcpy(tmp, path, sizeof(int)*4);
ans[anstop++] = tmp;
return;
}
for(int i = st; i<n; i++){
char* c = malloc(sizeof(char)*(i-st+2));
memcpy(c, s+st, sizeof(char)*(i-st+1));
c[i-st+1] = 0;
if(checkValid(c)){
path[pathtop++] = atoi(c);
if(pathtop == 4 && i+1 < n)goto nxt;
}else continue;
dfs(s, n, i+1);
nxt:
pathtop--;
}
}
char** restoreIpAddresses(char* s, int* returnSize) {
ans = malloc(sizeof(int*)*100);
path = malloc(sizeof(int)*21);
anstop = 0, pathtop = 0;
dfs(s, strlen(s), 0);
*returnSize = anstop;
return trans(ans, anstop, 4);
}
// way2 超过100%
#define SEG_COUNT 4
int segments[SEG_COUNT];
char** ans;
int ans_len;
void dfs(char* s, int segId, int segStart) {
// 如果找到了 4 段 IP 地址并且遍历完了字符串,那么就是一种答案
int len_s = strlen(s);
if (segId == SEG_COUNT) {
if (segStart == len_s) {
char* ipAddr = (char*)malloc(sizeof(char) * (len_s + 4));
int add = 0;
for (int i = 0; i < SEG_COUNT; ++i) {
int number = segments[i];
if (number >= 100) {
ipAddr[add++] = number / 100 + '0';
}
if (number >= 10) {
ipAddr[add++] = number % 100 / 10 + '0';
}
ipAddr[add++] = number % 10 + '0';
if (i != SEG_COUNT - 1) {
ipAddr[add++] = '.';
}
}
ipAddr[add] = 0;
ans = realloc(ans, sizeof(char*) * (ans_len + 1));
ans[ans_len++] = ipAddr;
}
return;
}
// 如果还没有找到 4 段 IP 地址就已经遍历完了字符串,那么提前回溯
if (segStart == len_s) {
return;
}
// 由于不能有前导零,如果当前数字为 0,那么这一段 IP 地址只能为 0
if (s[segStart] == '0') {
segments[segId] = 0;
dfs(s, segId + 1, segStart + 1);
return;
}
// 一般情况,枚举每一种可能性并递归
int addr = 0;
for (int segEnd = segStart; segEnd < len_s; ++segEnd) {
addr = addr * 10 + (s[segEnd] - '0');
if (addr > 0 && addr <= 0xFF) {
segments[segId] = addr;
dfs(s, segId + 1, segEnd + 1);
} else {
break;
}
}
}
char** restoreIpAddresses(char* s, int* returnSize) {
ans = (char**)malloc(0);
ans_len = 0;
dfs(s, 0, 0);
(*returnSize) = ans_len;
return ans;
}
子集
收集时不用if判断,直接ans[ansTop++]收集
例题78-子集 mid
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3] 输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
// step1
int* path;
int pathTop;
int** ans;
int ansTop;
int* anscnt;
void backtracing(int* nums, int n, int startIndex){
// step2-不用判断直接收集<=>树中结点全收集##############
int* tmp = malloc(sizeof(int)*pathTop);
memcpy(tmp, path, sizeof(int)*pathTop);
anscnt[ansTop] = pathTop;
ans[ansTop++] = tmp;
// step3
for(int i = startIndex; i<n; i++){
// push
path[pathTop++] = nums[i];
// dfs
backtracing(nums, n, i+1);
// pop
pathTop--;
}
}
int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
path = malloc(sizeof(int)*numsSize);
int ansSize = (int)pow(2, numsSize);
ans = malloc(sizeof(int*)*ansSize);
anscnt = malloc(sizeof(int)*ansSize);
ansTop = pathTop = 0;
backtracing(nums, numsSize, 0);
*returnSize = ansTop;
*returnColumnSizes = anscnt;
return ans;
}
例题90-子集 Ⅱ mid
给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的 子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
示例 1:
输入:nums = [1,2,2] 输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
子集 --> 直接收集;
去重 --> 数组快排后,backtracing回溯中for循环里面加if(i>startIndex && nums[i]==nums[i-1])continue; 判断.
// step1
int* path;
int pathTop;
int** ans;
int ansTop;
int* anscnt;
void backtracing(int* nums, int n, int startIndex){
// step2-不用判断直接收集<=>树中结点全收集
int* tmp = malloc(sizeof(int)*pathTop);
memcpy(tmp, path, sizeof(int)*pathTop);
anscnt[ansTop] = pathTop;
ans[ansTop++] = tmp;
// step3
for(int i = startIndex; i<n; i++){
if(i>startIndex && nums[i] == nums[i-1])continue;
// push
path[pathTop++] = nums[i];
// dfs
backtracing(nums, n, i+1);
// pop
pathTop--;
}
}
int cmp(const void* _a, const void* _b){
return *(int*)_a - *(int*)_b;
}
int** subsetsWithDup(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
path = malloc(sizeof(int)*numsSize);
int ansSize = (int)pow(2, numsSize);
ans = malloc(sizeof(int*)*ansSize);
anscnt = malloc(sizeof(int)*ansSize);
ansTop = pathTop = 0;
qsort(nums, numsSize, sizeof(int), cmp);
backtracing(nums, numsSize, 0);
*returnSize = ansTop;
*returnColumnSizes = anscnt;
return ans;
}
排列
for循环中i从0开始而不是startIndex,用visited数组记录树枝访问情况
例题46-全排列 mid
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
// step1
int* path;
int pathTop;
int** ans;
int ansTop;
bool* visited;
void backtracing(int* nums, int n, int** returnColumnSizes){
// step2
if(pathTop == n){
int* tmp = malloc(sizeof(int)*pathTop);
memcpy(tmp, path, sizeof(int)*pathTop);
(*returnColumnSizes)[ansTop] = n;
ans[ansTop++] = tmp;
return;
}
// step3
for(int i = 0; i<n; i++){ // ##################
if(visited[i] == true)continue; // ##################
path[pathTop++] = nums[i]; // push
visited[i] = true;
backtracing(nums, n, returnColumnSizes); // dfs
pathTop--; // pop
visited[i] = false;
}
}
int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
path = malloc(sizeof(int)*numsSize);
int ansSize = 750;
ans = malloc(sizeof(int*)*ansSize);
(*returnColumnSizes) = malloc(sizeof(int*)*ansSize);
pathTop = ansTop = 0;
visited = calloc(numsSize, sizeof(int));
backtracing(nums, numsSize, returnColumnSizes);
*returnSize = ansTop;
return ans;
}
例题47-全排列 Ⅱ mid
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2] 输出: [[1,1,2], [1,2,1], [2,1,1]]
qsort nums
判断if(i>0 && visited[i-1] == false && nums[i]==nums[i-1])continue;
int* path;
int pathTop;
int** ans;
int ansTop;
bool* visited;
void backtracing(int* nums, int n, int** returnColumnSizes){
if(pathTop == n){
int* tmp = malloc(sizeof(int)*pathTop);
memcpy(tmp, path, sizeof(int)*pathTop);
(*returnColumnSizes)[ansTop] = n;
ans[ansTop++] = tmp;
return;
}
for(int i = 0; i<n; i++){
if(visited[i] == true)continue;
if(i>0 && visited[i-1] == false && nums[i] == nums[i-1])continue;
path[pathTop++] = nums[i];
visited[i] = true;
backtracing(nums, n, returnColumnSizes);
pathTop--;
visited[i] = false;
}
}
int cmp(const void* _a, const void* _b){
return *(int*)_a - *(int*)_b;
}
int** permuteUnique(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
path = malloc(sizeof(int)*numsSize);
int ansSize = 750;
ans = malloc(sizeof(int*)*ansSize);
(*returnColumnSizes) = malloc(sizeof(int*)*ansSize);
pathTop = ansTop = 0;
visited = calloc(numsSize, sizeof(int));
qsort(nums, numsSize, sizeof(int), cmp);
backtracing(nums, numsSize, returnColumnSizes);
*returnSize = ansTop;
return ans;
}
N皇后
例题51-N皇后 hard
二叉树
横向为第row行选择不同列for
纵向为不同行dfs
// step1
char** chessboard;
char*** ans;
int ansTop;
bool isValid(char** chessboard,int n, int row, int col){
// 列
for (int i = 0; i < row; i++) {
if (chessboard[i][col] == 'Q')return false;
}
// 45度角是否有皇后
for (int i = row - 1, j = col - 1; i >=0 && j >= 0; i--, j--) {
if (chessboard[i][j] == 'Q')return false;
}
// 135度角是否有皇后
for(int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (chessboard[i][j] == 'Q')return false;
}
return true;
}
void backtracing(char** chessboard, int n, int row, int** returnColumnSizes){
// step2
if(row == n){
// push ans
char** tmp = malloc(sizeof(char*)*n);
for(int i = 0; i<n; i++){
tmp[i] = malloc(sizeof(char*)*(n+1));
memcpy(tmp[i], chessboard[i], sizeof(char)*(n+1));
}
(*returnColumnSizes)[ansTop] = n;
ans[ansTop++] = tmp;
return;
}
// step3
chessboard[row] = malloc(sizeof(char)*(n+1));
memset(chessboard[row], '.', n);
chessboard[row][n] = '\0';
for(int i = 0; i<n; i++){
if(isValid(chessboard, n, row, i)){
// push chessboard - Q
chessboard[row][i] = 'Q';
// dfs next row
backtracing(chessboard, n, row+1, returnColumnSizes);
// pop chessboard - .
chessboard[row][i] = '.';
}
}
}
char*** solveNQueens(int n, int* returnSize, int** returnColumnSizes) {
// init
chessboard = malloc(sizeof(char*)*n);
ans = malloc(sizeof(char**)*352);
(*returnColumnSizes) = malloc(sizeof(int*)*352);
ansTop = 0;
// backtracing
backtracing(chessboard, n, 0, returnColumnSizes);
//return
*returnSize = ansTop;
return ans;
}
解数独
例题37-解数独 hard
编写一个程序,通过填充空格来解决数独问题。
数独的解法需 遵循如下规则:
- 数字
1-9在每一行只能出现一次。 - 数字
1-9在每一列只能出现一次。 - 数字
1-9在每一个以粗实线分隔的3x3宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 '.' 表示。
示例 1:

输入:board = [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] 输出:[ ["5","3","4","6","7","8","9","1","2"], ["6","7","2","1","9","5","3","4","8"], ["1","9","8","3","4","2","5","6","7"], ["8","5","9","7","6","1","4","2","3"], ["4","2","6","8","5","3","7","9","1"], ["7","1","3","9","2","4","8","5","6"], ["9","6","1","5","3","7","2","8","4"], ["2","8","7","4","1","9","6","3","5"], ["3","4","5","2","8","6","1","7","9"] ]
bool isValid(int row, int col, char val, char** board) {
for (int i = 0; i < 9; i++) { // 行是否重复
if (board[row][i] == val) {
return false;
}
}
for (int j = 0; j < 9; j++) { // 列是否重复
if (board[j][col] == val) {
return false;
}
}
int startRow = (row / 3) * 3;
int startCol = (col / 3) * 3;
for (int i = startRow; i < startRow + 3; i++) { // 9方格是否重复
for (int j = startCol; j < startCol + 3; j++) {
if (board[i][j] == val ) {
return false;
}
}
}
return true;
}
bool backtracking(char** board, int m, int n) {
for (int i = 0; i < m; i++) { // 遍历行
for (int j = 0; j < n; j++) { // 遍历列
if (board[i][j] == '.') {
for (char k = '1'; k <= '9'; k++) {
if (isValid(i, j, k, board)) {
board[i][j] = k; // push
if (backtracking(board, m, n)) return true; // dfs
board[i][j] = '.'; // pop
}
}
return false; // 9个数都试完了,都不行,返回false
}
}
}
return true;
}
void solveSudoku(char** board, int boardSize, int* boardColSize) {
int m = boardSize, n = boardColSize[0];
backtracking(board, m, n);
}
转载自 CSDN-专业IT技术社区
原文链接:https://blog.csdn.net/2302_78434754/article/details/157327332



