有条件的全排列,允许重复,采用递归的方法
注意for循环的条件
function notRepeat(arr){
if(arr.length === 1){
return true;
}
for(var i = 0 ; i < arr.length - 1; i++)
{
if(arr[i] === arr[i+1])
return false;
}
return true;
}
function swap(arr, i, j){
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
return arr;
}
function perm(arr,start, end){
var count = 0;
if(start === end){
console.log(arr);
if(notRepeat(arr)){
return 1;
}else{
return 0;
}
}
for(var i = start ; i <= end ; i++){
arr = swap(arr, start, i);
count = count + perm(arr, start + 1, arr.length - 1);
arr = swap(arr, start, i);
}
return count;
}
function permAlone(str){
var arr = str.split("");
var count = perm(arr, 0 , arr.length -1 );
return count;
}
var a = permAlone("aab");
console.log(a);