剑指 Offer 38. 字符串的排列
题目来源:剑指 Offer 38. 字符串的排列
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
方法一:回溯
/** * @param {string} s * @return {string[]} */ var permutation = function(s) { let n = s.length; let perm = []; let res = []; let vis = []; let arr = Array.from(s).sort(); var backTrack = function (i) { if(i === n){ res.push( perm.join('')); return ; } for(let j=0;j<n;j++){ if(vis[j] || (j>0 && !vis[j-1] && arr[j-1] === arr[j]) ){ continue; } perm.push(arr[j]); vis[j] = true; backTrack(i+1); perm.pop(); vis[j] = false; } } backTrack(0); return res; };
let s = 'abc';
console.log(s, permutation(s))
s = 'aca';
console.log(s, permutation(s))
方法二:下一个排列
/** * @param {string} s * @return {string[]} */ var permutation = function(s) { let n = s.length; let res = []; let arr = Array.from(s).sort(); var nextPermutation = (a)=>{ let i = n - 2; while(i>=0 && a[i] >= a[i+1]){ i--; } if(i<0){ return false; } let j = n - 1; while(j>=0 && a[i]>=a[j]){ j--; } [a[i], a[j]] = [a[j], a[i]]; arr = [].concat(a.slice(0, i+1), a.slice(i+1).reverse()); return true; } do{ res.push(arr.join('')) }while(nextPermutation(arr)) return res; };
示例:
输入:s = "abc" 输出:["abc","acb","bac","bca","cab","cba"]
限制:
1 <= s 的长度 <= 8