作者:ccmm6688 | 来源:互联网 | 2023-10-10 09:04
问题很简单,但是让我头疼,例如,我有4个数字数组,但最多可以有20个数字.按以下顺序给出:[1][2][4][5]我需要获取此数字的所有组合,但数字不能被置换,因此顺序保持不变,我
问题很简单,但是让我头疼,
例如,我有4个数字数组,但最多可以有20个数字.
按以下顺序给出:
[1] [2] [4] [5]
我需要获取此数字的所有组合,但数字不能被置换,因此顺序保持不变,我将举一个示例说明我要获取的内容:
[1] [ ] [4] [5]
[1] [2] [ ] [5]
[ ] [2] [4] [5]
[ ] [ ] [ ] [5]
and even
[ ] [ ] [ ] [ ]
结果数组将包含结果数字的子数组
更新:空数组是可选的,
[1] [4]
Or
[2] [4] [5]
也可以,并发症少.
解决方法:
如果您意识到我们想要完成的事情实际上是递归的,那么您想做的事情就可以轻松完成.对于每个子部分,我们需要做出选择:我们添加一个空格,或者从列表中添加一个数字.
function wonkyPermutations( $numbers ) {
return wonkyPermutationsWithSpaces( Array(), $numbers, count( $numbers ) );
}
function wonkyPermutationsWithSpaces( $prefix, $numbers, $maxlength ) {
if( $maxlength == 0 ) {
//We can't add anymore
return Array( $prefix );
} else {
//We have two choices: We either add a space, or we don't.
$prefix1 = $prefix;
$prefix1[] = NULL;
$prefix2 = $prefix;
$prefix2[] = $numbers[0];
$suffix1 = wonkyPermutationsWithSpaces( $prefix1, array_slice( $numbers, 1 ), $maxlength - 1 );
$suffix2 = wonkyPermutationsWithSpaces( $prefix2, array_slice( $numbers, 1 ), $maxlength - 1 );
return array_merge( $suffix1, $suffix2 );
}
}
$a = Array( 1, 2, 3, 4 );
var_dump( wonkyPermutations( $a ) );