leetcode题解日练--2016.09.06

2024-03-06 10:38

本文主要是介绍leetcode题解日练--2016.09.06,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

不给自己任何借口

今日题目:

1、数独的解

2、N-皇后II

3、N-皇后

今日摘录:

大抵浮生若梦,姑且此处销魂。
——曾国藩

37. Sudoku Solver | Difficulty: Hard

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character ‘.’.

You may assume that there will be only one unique solution.

A sudoku puzzle…

…and its solution numbers marked in red.

tag:回溯|哈希表
题意:数独的解

思路:
1、dfs+回溯

class Solution {
public:void solveSudoku(vector<vector<char>>& board){solve(board);}bool solve(vector<vector<char>>& board) {for(int r = 0;r<9;r++){for(int c=0;c<9;c++){if(board[r][c]=='.'){for (char k = '1'; k <= '9'; k++){if(isvalid(board,r,c,k)){board[r][c] = k;if(solve(board))    return true;board[r][c] = '.';}}return false;}}}return true;}bool isvalid(vector<vector<char>>& board,int row,int col,char k){for(int i=0;i<9  ;i++)if(board[i][col]==k)    return false;for(int i=0;i<9 ;i++)if(board[row][i]==k)    return false;for(int i=(row/3)*3;i<(row/3+1)*3 ;i++){for(int j=(col/3)*3;j<(col/3+1)*3;j++){if(board[i][j]==k)    return false;}}return true;}
};

结果:53ms

52. N-Queens II | Difficulty: Hard

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

tag:回溯

题意:找到N皇后有多少个解
思路:
1、经典的回溯思想,边放置边剪枝。

class Solution {
public:
int totalNQueens(int n) {int res = 0;//cols代表因为列不冲突的情况,main是主对角线,anti是辅对角线。为何对角线的标志位数组要比cols大呢?vector<bool> cols(n,true);vector<bool> main(2*n-1,true);vector<bool> anti(2*n-1,true);dfs(0,res,cols,main,anti);return res;
}
void dfs(int row,int&res,vector<bool> &cols,vector<bool> &main,vector<bool> &anti)
{if(row==cols.size()){res++;return ;}for(int col = 0;col<cols.size();col++){if(cols[col] && main[row-col+cols.size()-1]&&anti[row+col]){cols[col] = main[row-col+cols.size()-1]=anti[row+col] = false;dfs(row+1,res,cols,main,anti);cols[col] = main[row-col+cols.size()-1]=anti[row+col] = true;}}return;
}
};

结果:13ms

2、
使用位运算的方法:
row用一个Nbit位的数代表哪些位置是接下来还能放的,哪些位置是不能放的。
main:主对角线,代表主对角线对下一行选取位置的影响
anti:副对角线,代表副对角线对下一行选取位置的影响

class Solution {
public:void queenBit(int row,int main,int anti,const int all_queen)
{if(row!=all_queen){int pos = all_queen & ~(row|main|anti);while(pos!=0){int p = pos&-pos;pos-=p;queenBit(row+p,(main+p)<<1,(anti+p)>>1,all_queen);}}else{res++;return ;}
}int totalNQueens(int n) {res = 0;int all_queen = (1<<n)-1;queenBit(0,0,0,all_queen);return res;
}
private:int res;};

结果:0ms

51. N-Queens | Difficulty: Hard

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
[“.Q..”, // Solution 1
“…Q”,
“Q…”,
“..Q.”],

[“..Q.”, // Solution 2
“Q…”,
“…Q”,
“.Q..”]
]
tag:回溯

题意:找到N皇后的每个解是什么。
思路:
1、经典的回溯思想,边放置边剪枝。

class Solution {
public:void dfs(int row,vector<vector<string>>&res,vector<string>path,vector<bool> &cols,vector<bool> &main,vector<bool> &anti,const string str){if(row==cols.size()){res.push_back(path);return ;}for(int col = 0;col<cols.size();col++){if(cols[col] && main[row+col]&&anti[row-col+cols.size()-1]){string tmp = str;tmp[col] = 'Q';path.push_back(tmp);cols[col] = main[row+col]=anti[row-col+cols.size()-1] = false;dfs(row+1,res,path,cols,main,anti,str);path.pop_back();tmp[col] = '.';cols[col] = main[row+col]=anti[row-col+cols.size()-1] = true;}}return;}vector<vector<string>> solveNQueens(int n) {vector<bool> cols(n,true);vector<bool> main(2*n-1,true);vector<bool> anti(2*n-1,true);vector<string> path;string str = dot.substr(0,n);dfs(0,res,path,cols,main,anti,str);return res;}
private:vector<vector<string>>res;string dot = "......................";};

结果:29ms

2、
使用位运算的方法:
row用一个Nbit位的数代表哪些位置是接下来还能放的,哪些位置是不能放的。
main:主对角线,代表主对角线对下一行选取位置的影响
anti:副对角线,代表副对角线对下一行选取位置的影响

class Solution {
public:void queenBit(int row,int main,int anti,const int all_queen,const string str,vector<string>&path){if(row!=all_queen){int pos = all_queen & ~(row|main|anti);while(pos!=0){int p = pos&-pos;pos-=p;string tmp = str;int i = log10(p)/log10(2);tmp[i] = 'Q';path.push_back(tmp);queenBit(row+p,(main+p)<<1,(anti+p)>>1,all_queen,str,path);path.pop_back();tmp[i] = '.';}}else{res.push_back(path);return ;}}vector<vector<string>> solveNQueens(int n) {int all_queen = (1<<n)-1;string str = dot.substr(0,n);vector<string> path;queenBit(0,0,0,all_queen,str,path);return res;}
private:vector<vector<string>>res;string dot = "......................";
};

结果:3ms

这篇关于leetcode题解日练--2016.09.06的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/779792

相关文章

哈希leetcode-1

目录 1前言 2.例题  2.1两数之和 2.2判断是否互为字符重排 2.3存在重复元素1 2.4存在重复元素2 2.5字母异位词分组 1前言 哈希表主要是适合于快速查找某个元素(O(1)) 当我们要频繁的查找某个元素,第一哈希表O(1),第二,二分O(log n) 一般可以分为语言自带的容器哈希和用数组模拟的简易哈希。 最简单的比如数组模拟字符存储,只要开26个c

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

leetcode-24Swap Nodes in Pairs

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode swapPairs(L

leetcode-23Merge k Sorted Lists

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode mergeKLists

C++ | Leetcode C++题解之第393题UTF-8编码验证

题目: 题解: class Solution {public:static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num &

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟)

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟) 题目描述 给定一个链表,链表中的每个节点代表一个整数。链表中的整数由 0 分隔开,表示不同的区间。链表的开始和结束节点的值都为 0。任务是将每两个相邻的 0 之间的所有节点合并成一个节点,新节点的值为原区间内所有节点值的和。合并后,需要移除所有的 0,并返回修改后的链表头节点。 思路分析 初始化:创建一个虚拟头节点

C语言 | Leetcode C语言题解之第393题UTF-8编码验证

题目: 题解: static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num & MASK1) == 0) {return

【JavaScript】LeetCode:16-20

文章目录 16 无重复字符的最长字串17 找到字符串中所有字母异位词18 和为K的子数组19 滑动窗口最大值20 最小覆盖字串 16 无重复字符的最长字串 滑动窗口 + 哈希表这里用哈希集合Set()实现。左指针i,右指针j,从头遍历数组,若j指针指向的元素不在set中,则加入该元素,否则更新结果res,删除集合中i指针指向的元素,进入下一轮循环。 /*** @param

C - Word Ladder题解

C - Word Ladder 题解 解题思路: 先输入两个字符串S 和t 然后在S和T中寻找有多少个字符不同的个数(也就是需要变换多少次) 开始替换时: tips: 字符串下标以0开始 我们定义两个变量a和b,用于记录当前遍历到的字符 首先是判断:如果这时a已经==b了,那么就跳过,不用管; 如果a大于b的话:那么我们就让s中的第i项替换成b,接着就直接输出S就行了。 这样

LeetCode:64. 最大正方形 动态规划 时间复杂度O(nm)

64. 最大正方形 题目链接 题目描述 给定一个由 0 和 1 组成的二维矩阵,找出只包含 1 的最大正方形,并返回其面积。 示例1: 输入: 1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0输出: 4 示例2: 输入: 0 1 1 0 01 1 1 1 11 1 1 1 11 1 1 1 1输出: 9 解题思路 这道题的思路是使用动态规划