欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實(shí)現(xiàn)窮舉排列(permutation)算法謎題解答

 更新時(shí)間:2014年12月29日 09:34:24   投稿:junjie  
這篇文章主要介紹了JavaScript實(shí)現(xiàn)窮舉排列(permutation)算法謎題解答,窮舉排列是指窮舉一個(gè)數(shù)組中各個(gè)元素的排列,需要的朋友可以參考下

謎題

窮舉一個(gè)數(shù)組中各個(gè)元素的排列

策略

減而治之、遞歸

JavaScript解


復(fù)制代碼 代碼如下:

/**
 * Created by cshao on 12/23/14.
 */

function getPermutation(arr) {
  if (arr.length == 1) {
    return [arr];
  }

  var permutation = [];
  for (var i=0; i<arr.length; i++) {
    var firstEle = arr[i];
    var arrClone = arr.slice(0);
    arrClone.splice(i, 1);
    var childPermutation = getPermutation(arrClone);
    for (var j=0; j<childPermutation.length; j++) {
      childPermutation[j].unshift(firstEle);
    }
    permutation = permutation.concat(childPermutation);
  }
  return permutation;
}

var permutation = getPermutation(['a','b','c']);
console.dir(permutation);

結(jié)果


復(fù)制代碼 代碼如下:

[ [ 'a', 'b', 'c' ],
  [ 'a', 'c', 'b' ],
  [ 'b', 'a', 'c' ],
  [ 'b', 'c', 'a' ],
  [ 'c', 'a', 'b' ],
  [ 'c', 'b', 'a' ] ]

相關(guān)文章

最新評(píng)論