一、全排列
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
/*
DFS:深度遍历求解
*/
var permute = function(nums) {
let res = []
const dfs = (path)=>{
// 出口条件
if(path.length == nums.length){
//将结果放进数组里
res.push([...path])
return
}
for(let i =0;i<nums.length;i++){
//减少重复的遍历
if(path.includes(nums[i])) continue
path.push(nums[i])
dfs(path)
// 最后结果出栈
path.pop()
}
}
dfs([])
return res
};
二、全排列2(要求重复元素也排列,并去重)
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
var permuteUnique = function (nums) {
let res = []
let path = []
//定义一个记录字符串使用记录的数组
let used = Array(nums.length).fill(false)
const dfs = (path,used) => {
if (path.length === nums.length) {
res.push([...path])
return
}
// 数组去重,防止重复的循环
// 用于防止:112后,第二个循环又出现,112
let set = new Set()
for (let i = 0; i < nums.length; i++) {
if(!used[i] && !set.has(nums[i])){
set.add(nums[i])
path.push(nums[i])
used[i] = true
dfs(path,used)
path.pop()
used[i] = false
}
}
}
dfs(path,used)
return res
};
三、字符串的全排列(不含重复)
例:输入 " abc "
输出:[‘abc’, ‘acb’, ‘bac’, ‘bca’, ‘cab’, ‘cba’]
function permuteUnique(target){
let str = ''
let res = []
const dfs = (str)=>{
if(str.length === target.length){
res.push(str)
return
}
for(let i =0;i<target.length;i++){
if(str.indexOf(target[i]) != -1) continue
dfs(str+target[i])
}
}
dfs(str)
return res
}
console.log(permuteUnique('abc')); // ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
四、字符串的全排列(含重复,去重)
输入:" aba "
输出:[‘aba’, ‘aab’, ‘baa’]
function permuteUnique(target){
let str = ''
// 字符串去重使用
let res = new Set()
let used = Array(target.length).fill(false)
const dfs = (str,used)=>{
if(str.length === target.length){
res.add(str)
return
}
for(let i =0;i<target.length;i++){
if(!used[i]){
used[i] = true
dfs(str+target[i],used)
used[i] = false
}
}
}
dfs(str,used)
return Array.from(res)
}
console.log(permuteUnique('aba')); //['aba', 'aab', 'baa']