Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique.
For example, aab should return 2 because it has 6 total permutations (aab, aab, aba, aba, baa, baa), but only 2 of them (aba and aba) don't have the same letter (in this case a) repeating.
function permutation(s) { if (s.length === 1) { return [s]; } if (s.length === 2) { return [s, s[1] + s[0]]; } let arr = []; for (let c of s) { for (let item of permutation(s.replace(c, '')).map(v => c + v)) { arr.push(item); } } return arr; } function permAlone(str) { let n = 0; for (let s of permutation(str)) { n++; for (let i in s) { if (i < s.length - 1 && s[i] === s[parseInt(i) + 1]) { n--; break; } } } return n; }
思路:全排列+排除法
This post belongs to Column 「算法专栏」 .