Skip to content

Commit

Permalink
feat: 算法-二分与回溯
Browse files Browse the repository at this point in the history
  • Loading branch information
duanlvxin committed Aug 21, 2024
1 parent 0af8450 commit e334c9e
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ db.json
node_modules/
public/
.deploy*/
_multiconfig.yml
_multiconfig.yml
.vscode/
73 changes: 73 additions & 0 deletions source/_posts/算法-二分与回溯.md
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/

0 comments on commit e334c9e

Please sign in to comment.