js给出所有组合

clipboard.png

如何得出多有组合?
用js
有好的思路指点一下吗~

阅读 3.6k
4 个回答

考来的。。。

function permute(input) {
  var permArr = [],
  usedChars = [];
  function main(input){
    var i, ch;
    for (i = 0; i < input.length; i++) {
      ch = input.splice(i, 1)[0];
      usedChars.push(ch);
      if (input.length == 0) {
        permArr.push(usedChars.slice());
      }
      main(input);
      input.splice(i, 0, ch);
      usedChars.pop();
    }
    return permArr;
  }
  return main(input).join('\n');
};
console.log(permute(['foo','bar','hello','world']));
var arr = ['foo', 'bar', 'hello', 'world']; 

// 4 3 2 1 
var first = {}
var result = []; 
arr.forEach((first, idx, its) => {
    its.filter(e => e!==first).forEach((sec, idx, its) => {
        its.filter(e => e!==sec).forEach((third, idx, its)=> { 
            its.filter(e => e!=third).forEach((forth, idx, its) => {
                console.log(first, sec, third, forth); 
                result.push(first + sec + third + forth); 
            }); 
        });
    });
});

clipboard.png

= = 丧心病狂的遍历。。。

可以用有向图方法,得出四个节点所有路径

栈和队列

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题