Merge branch 'youngyangyang04:master' into master

This commit is contained in:
xllpiupiu
2021-05-25 09:17:25 +08:00
10 changed files with 325 additions and 22 deletions

View File

@ -131,6 +131,27 @@ class Solution {
Python Python
Go Go
```go
func swapPairs(head *ListNode) *ListNode {
dummy := &ListNode{
Next: head,
}
//head=list[i]
//pre=list[i-1]
pre := dummy
for head != nil && head.Next != nil {
pre.Next = head.Next
next := head.Next.Next
head.Next.Next = head
head.Next = next
//pre=list[(i+2)-1]
pre = head
//head=list[(i+2)]
head = next
}
return dummy.Next
}
```
Javascript: Javascript:
```javascript ```javascript

View File

@ -291,7 +291,61 @@ Python
Go Go
Javascript:
```Javascript
var solveSudoku = function(board) {
function isValid(row, col, val, board) {
let len = board.length
// 行不能重复
for(let i = 0; i < len; i++) {
if(board[row][i] === val) {
return false
}
}
// 列不能重复
for(let i = 0; i < len; i++) {
if(board[i][col] === val) {
return false
}
}
let startRow = Math.floor(row / 3) * 3
let startCol = Math.floor(col / 3) * 3
for(let i = startRow; i < startRow + 3; i++) {
for(let j = startCol; j < startCol + 3; j++) {
if(board[i][j] === val) {
return false
}
}
}
return true
}
function backTracking() {
for(let i = 0; i < board.length; i++) {
for(let j = 0; j < board[0].length; j++) {
if(board[i][j] !== '.') continue
for(let val = 1; val <= 9; val++) {
if(isValid(i, j, `${val}`, board)) {
board[i][j] = `${val}`
if (backTracking()) {
return true
}
board[i][j] = `.`
}
}
return false
}
}
return true
}
backTracking(board)
return board
};
```
----------------------- -----------------------

View File

@ -430,6 +430,65 @@ func solveNQueens(n int) [][]string {
} }
``` ```
Javascript:
```Javascript
var solveNQueens = function(n) {
function isValid(row, col, chessBoard, n) {
for(let i = 0; i < row; i++) {
if(chessBoard[i][col] === 'Q') {
return false
}
}
for(let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if(chessBoard[i][j] === 'Q') {
return false
}
}
for(let i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if(chessBoard[i][j] === 'Q') {
return false
}
}
return true
}
function transformChessBoard(chessBoard) {
let chessBoardBack = []
chessBoard.forEach(row => {
let rowStr = ''
row.forEach(value => {
rowStr += value
})
chessBoardBack.push(rowStr)
})
return chessBoardBack
}
let result = []
function backtracing(row,chessBoard) {
if(row === n) {
result.push(transformChessBoard(chessBoard))
return
}
for(let col = 0; col < n; col++) {
if(isValid(row, col, chessBoard, n)) {
chessBoard[row][col] = 'Q'
backtracing(row + 1,chessBoard)
chessBoard[row][col] = '.'
}
}
}
let chessBoard = new Array(n).fill([]).map(() => new Array(n).fill('.'))
backtracing(0,chessBoard)
return result
};
```
----------------------- -----------------------

View File

@ -370,23 +370,21 @@ class Solution {
Python Python
```python ```python3
class Solution: class Solution:
result: List[List[int]] = []
path: List[int] = []
def combine(self, n: int, k: int) -> List[List[int]]: def combine(self, n: int, k: int) -> List[List[int]]:
self.result = [] res=[] #存放符合条件结果的集合
self.combineHelper(n, k, 1) path=[] #用来存放符合条件结果
return self.result def backtrack(n,k,startIndex):
if len(path) == k:
def combineHelper(self, n: int, k: int, startIndex: int): res.append(path[:])
if (l := len(self.path)) == k: return
self.result.append(self.path.copy()) for i in range(startIndex,n+1):
return path.append(i) #处理节点
for i in range(startIndex, n - (k - l) + 2): backtrack(n,k,i+1) #递归
self.path.append(i) path.pop() #回溯,撤销处理的节点
self.combineHelper(n, k, i + 1) backtrack(n,k,1)
self.path.pop() return res
``` ```
javascript javascript
```javascript ```javascript
@ -438,8 +436,6 @@ func backtrack(n,k,start int,track []int){
``` ```
----------------------- -----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
* B站视频[代码随想录](https://space.bilibili.com/525438321) * B站视频[代码随想录](https://space.bilibili.com/525438321)

View File

@ -176,9 +176,49 @@ class Solution {
``` ```
Python Python
```python3
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res=[] #存放符合条件结果的集合
path=[] #用来存放符合条件结果
def backtrack(n,k,startIndex):
if len(path) == k:
res.append(path[:])
return
for i in range(startIndex,n-(k-len(path))+2): #优化的地方
path.append(i) #处理节点
backtrack(n,k,i+1) #递归
path.pop() #回溯,撤销处理的节点
backtrack(n,k,1)
return res
```
Go Go
```Go
var res [][]int
func combine(n int, k int) [][]int {
res=[][]int{}
if n <= 0 || k <= 0 || k > n {
return res
}
backtrack(n, k, 1, []int{})
return res
}
func backtrack(n,k,start int,track []int){
if len(track)==k{
temp:=make([]int,k)
copy(temp,track)
res=append(res,temp)
}
if len(track)+n-start+1 < k {
return
}
for i:=start;i<=n;i++{
track=append(track,i)
backtrack(n,k,i+1,track)
track=track[:len(track)-1]
}
}
```

View File

@ -580,8 +580,10 @@ tree2 的前序遍历是[1 2 3] 后序遍历是[3 2 1]。
## 其他语言版本 ## 其他语言版本
Java Java
106.从中序与后序遍历序列构造二叉树
```java ```java
class Solution { class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) { public TreeNode buildTree(int[] inorder, int[] postorder) {
@ -617,8 +619,43 @@ class Solution {
} }
``` ```
105.从前序与中序遍历序列构造二叉树
```java
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return helper(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}
public TreeNode helper(int[] preorder, int preLeft, int preRight,
int[] inorder, int inLeft, int inRight) {
// 递归终止条件
if (inLeft > inRight || preLeft > preRight) return null;
// val 为前序遍历第一个的值,也即是根节点的值
// idx 为根据根节点的值来找中序遍历的下标
int idx = inLeft, val = preorder[preLeft];
TreeNode root = new TreeNode(val);
for (int i = inLeft; i <= inRight; i++) {
if (inorder[i] == val) {
idx = i;
break;
}
}
// 根据 idx 来递归找左右子树
root.left = helper(preorder, preLeft + 1, preLeft + (idx - inLeft),
inorder, inLeft, idx - 1);
root.right = helper(preorder, preLeft + (idx - inLeft) + 1, preRight,
inorder, idx + 1, inRight);
return root;
}
}
```
Python Python
105.从前序与中序遍历序列构造二叉树 105.从前序与中序遍历序列构造二叉树
```python ```python
# Definition for a binary tree node. # Definition for a binary tree node.
# class TreeNode: # class TreeNode:
@ -637,6 +674,7 @@ class Solution:
return root return root
``` ```
106.从中序与后序遍历序列构造二叉树 106.从中序与后序遍历序列构造二叉树
```python ```python
# Definition for a binary tree node. # Definition for a binary tree node.
# class TreeNode: # class TreeNode:

View File

@ -347,6 +347,42 @@ class Solution {
} }
``` ```
0113.路径总和-ii
```java
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res; // 非空判断
List<Integer> path = new LinkedList<>();
preorderDFS(root, targetSum, res, path);
return res;
}
public void preorderDFS(TreeNode root, int targetSum, List<List<Integer>> res, List<Integer> path) {
path.add(root.val);
// 遇到了叶子节点
if (root.left == null && root.right == null) {
// 找到了和为 targetSum 的路径
if (targetSum - root.val == 0) {
res.add(new ArrayList<>(path));
}
return; // 如果和不为 targetSum返回
}
if (root.left != null) {
preorderDFS(root.left, targetSum - root.val, res, path);
path.remove(path.size() - 1); // 回溯
}
if (root.right != null) {
preorderDFS(root.right, targetSum - root.val, res, path);
path.remove(path.size() - 1); // 回溯
}
}
}
```
Python Python
0112.路径总和 0112.路径总和

View File

@ -183,6 +183,26 @@ func reverseString(s []byte) {
} }
``` ```
javaScript:
```js
/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
var reverseString = function(s) {
return s.reverse();
};
var reverseString = function(s) {
let l = -1, r = s.length;
while(++l < --r) [s[l], s[r]] = [s[r], s[l]];
return s;
};
```

View File

@ -168,6 +168,26 @@ class Solution(object):
Go Go
javaScript:
```js
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var reverseStr = function(s, k) {
const len = s.length;
let resArr = s.split("");
for(let i = 0; i < len; i += 2 * k) {
let l = i - 1, r = i + k > len ? len : i + k;
while(++l < --r) [resArr[l], resArr[r]] = [resArr[r], resArr[l]];
}
return resArr.join("");
};
```

View File

@ -346,8 +346,27 @@ class Solution {
Python Python
```python
class Solution:
def minCameraCover(self, root: TreeNode) -> int:
result = 0
def traversal(cur):
nonlocal result
if not cur:
return 2
left = traversal(cur.left)
right = traversal(cur.right)
if left == 2 and right == 2:
return 0
elif left == 0 or right == 0:
result += 1
return 1
elif left == 1 or right == 1:
return 2
else: return -1
if traversal(root) == 0: result += 1
return result
```
Go Go