「DFS算法」实现一个数组,或者字符串的 “全排列” 算法

一、全排列

给定一个不含重复数字的数组 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']
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值