我有一串数字“ 123456”,我想以所有可能的方式将它们分开。
所以
1 23456 1 2 3456 1 23 45 6 1234 5 6 and so on
我尝试过的…
循环遍历len-1并拆分每个索引,但是从逻辑上讲,它错过了许多可能的情况。
您可以尝试如下的递归函数…
<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个组合)。有人可以确认吗?