get all combinations for a string

前端 未结 8 1705
傲寒
傲寒 2020-12-01 19:34

I\'m trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting wit

8条回答
  •  旧时难觅i
    2020-12-01 20:24

    This is a recursive solution that I think is very easy to understand.

    var tree = function(leafs) {
      var branches = [];
      if (leafs.length == 1) return leafs;
      for (var k in leafs) {
        var leaf = leafs[k];
        tree(leafs.join('').replace(leaf, '').split('')).concat("").map(function(subtree) {
          branches.push([leaf].concat(subtree));
        });
      }
      return branches;
    };
    console.log(tree("abc".split('')).map(function(str) {
      return str.join('')
    }))

提交回复
热议问题