-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
75 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,4 +5,5 @@ db.json | |
node_modules/ | ||
public/ | ||
.deploy*/ | ||
_multiconfig.yml | ||
_multiconfig.yml | ||
.vscode/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
--- | ||
title: 算法-二分与回溯 | ||
date: 2024-08-19 22:53:44 | ||
categories: | ||
- 数据结构与算法 | ||
tags: | ||
- js | ||
- 算法 | ||
cover: https://assets.leetcode.cn/aliyun-lc-upload/uploaded_files/2021/03/73c9f099-abbe-4d94-853f-f8abffd459cd/leetcode.png | ||
--- | ||
|
||
**二分和回溯在代码书写上是有明确的公式的。** | ||
|
||
## 二分 | ||
|
||
前提:有序数组 | ||
思想:判断中间位置的值大小,对半分去找 | ||
|
||
```js | ||
function search(arr, target) { | ||
let low = 0, high = arr.length - 1 | ||
while(low <= high) { | ||
let mid = low + ((high - low) >> 1) | ||
if(arr[mid] === target) { | ||
return mid; | ||
}else if(arr[mid]<target){ | ||
low = mid + 1; | ||
} else { | ||
high = mid -1; | ||
} | ||
} | ||
return -1; | ||
} | ||
``` | ||
|
||
【相关题库】:https://leetcode.cn/tag/binary-search/problemset/ | ||
【经典题目】: | ||
求平方根 - https://leetcode.cn/problems/sqrtx/description/ | ||
寻找旋转排序数组中的最小值 - https://leetcode.cn/problems/find-minimum-in-rotated-sorted-array/description/ | ||
|
||
## 回溯 | ||
|
||
```js | ||
function combine(n, k) { | ||
let result = [], path = [] | ||
|
||
function backTrace() { | ||
// 停止条件 | ||
if(condition) { | ||
result.push([...path]); | ||
return; | ||
} | ||
|
||
// 尝试一个,然后去掉这个尝试,进行下一轮 | ||
for(condition) { | ||
path.push(i); | ||
backTrace(); | ||
path.pop(); | ||
} | ||
} | ||
|
||
backTrace(); | ||
return result; | ||
} | ||
``` | ||
|
||
【相关题库】:https://leetcode.cn/tag/backtracking/problemset/ | ||
【经典题目】: | ||
组合 - https://leetcode.cn/problems/combinations/description/ | ||
组合总数 - https://leetcode.cn/problems/combination-sum/description/ | ||
组合总数2 - https://leetcode.cn/problems/combination-sum-ii/description/ | ||
全排列 - https://leetcode.cn/problems/permutations/description/ | ||
全排列2 - https://leetcode.cn/problems/permutations-ii/description/ |