在javascript中拆分一串数字中的所有可能的组合?

时间:2015-12-26 04:20:53

标签: javascript string algorithm permutation

我有一串数字" 123456"我希望以各种可能的方式将它们分开。

所以

1 23456
1 2 3456
1 23 45 6
1234 5 6
and so on 

我尝试过的......

循环遍历len-1,并拆分每个索引,但逻辑上它错过了很多可能的场景。

1 个答案:

答案 0 :(得分:2)

您可以尝试下面的递归函数......

<script lang="javascript">

  // Split string into all combinations possible
  function splitAllWays(result, left, right){
    // Push current left + right to the result list
    result.push(left.concat(right));
    //document.write(left.concat(right) + '<br />');

    // If we still have chars to work with in the right side then keep splitting
    if (right.length > 1){
      // For each combination left/right split call splitAllWays()
      for(var i = 1; i < right.length; i++){
        splitAllWays(result, left.concat(right.substring(0, i)), right.substring(i));
      }
    }

    // Return result
    return result;
  };

  var str = "123456";
  var ans = splitAllWays([], [], str);

</script>

<强>结果

123456
1,23456
1,2,3456
1,2,3,456
1,2,3,4,56
1,2,3,4,5,6
1,2,3,45,6
1,2,34,56
1,2,34,5,6
1,2,345,6
1,23,456
1,23,4,56
1,23,4,5,6
1,23,45,6
1,234,56
1,234,5,6
1,2345,6
12,3456
12,3,456
12,3,4,56
12,3,4,5,6
12,3,45,6
12,34,56
12,34,5,6
12,345,6
123,456
123,4,56
123,4,5,6
123,45,6
1234,56
1234,5,6
12345,6

我认为这是正确的结果(32种组合)。有人可以证实吗?

相关问题