Skip to content

Commit 9cca49f

Browse files
add: 全排列算法
1 parent 3a04ad1 commit 9cca49f

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/arr/readme.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,19 @@
44

55
2、合并有序数组:
66
用两个指针,从后往前移动,不断对比加入到新的数组。
7+
8+
3、有一种去深度遍历的方式,很多时候也可以看成是暴力方式,也就是回溯算法,将不符合要求的排除掉。
9+
```js
10+
result = []
11+
function backtrack() {
12+
if(满足条件) {
13+
resule.push(path)
14+
return
15+
}
16+
for() {
17+
// 做选择(前序遍历)
18+
backtrack(path, list)
19+
// 撤销选择(后续遍历)
20+
}
21+
}
22+
```

src/arr/全排列.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// 给定一个不含重复数字的数组nums,返回其所有可能的全排列。你可以按照任何顺序返回答案
2+
// 输入:nums = [1, 2, 3]
3+
// 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
4+
// 思路:从脑海里要有树的概念,一层层树都是递归去完成,然后通过已经重复来剪去一些小树枝
5+
function permute(nums) {
6+
const res = []
7+
backtrack([])
8+
return res
9+
function backtrack(path) {
10+
if(path.length === nums.length) {
11+
res.push(path)
12+
return
13+
}
14+
for (let i = 0; i < nums.length; i++) {
15+
if(path.includes(nums[i])) { continue; }
16+
backtrack(path.concat(nums[i]))
17+
}
18+
}
19+
};
20+
21+
console.log(permute([1,2,3]))
22+
23+
24+
25+
26+
27+
28+
29+
30+
31+
32+
33+
34+
35+
36+
// 正确答案
37+
/**
38+
const res = []
39+
backtrack([])
40+
return res
41+
function backtrack(path) {
42+
if(path.length === nums.length) {
43+
res.push(path)
44+
return
45+
}
46+
for (let i = 0; i < nums.length; i++) {
47+
if(path.includes(nums[i])) { continue; }
48+
backtrack(path.concat(nums[i]))
49+
}
50+
}
51+
*/

0 commit comments

Comments
 (0)