php 获取字符串行数,Php递归以获取字符串的所有可能性

这里有一个算法,

function getCombinations($base,$n){

$baselen = count($base);

if($baselen == 0){

return;

}

if($n == 1){

$return = array();

foreach($base as $b){

$return[] = array($b);

}

return $return;

}else{

//get one level lower combinations

$oneLevelLower = getCombinations($base,$n-1);

//for every one level lower combinations add one element to them that the last element of a combination is preceeded by the element which follows it in base array if there is none, does not add

$newCombs = array();

foreach($oneLevelLower as $oll){

$lastEl = $oll[$n-2];

$found = false;

foreach($base as $key => $b){

if($b == $lastEl){

$found = true;

continue;

//last element found

}

if($found == true){

//add to combinations with last element

if($key < $baselen){

$tmp = $oll;

$newCombination = array_slice($tmp,0);

$newCombination[]=$b;

$newCombs[] = array_slice($newCombination,0);

}

}

}

}

}

return $newCombs;

}

我知道它在任何方面都不有效,但在小的设备中使用应该不是问题

第一个基参数是一个数组,包含生成组合时要考虑的元素。

对于简单的使用和输出:

var_dump(getCombinations(array("a","b","c","d"),2));

输出是

array

0 =>

array

0 => string 'a' (length=1)

1 => string 'b' (length=1)

1 =>

array

0 => string 'a' (length=1)

1 => string 'c' (length=1)

2 =>

array

0 => string 'a' (length=1)

1 => string 'd' (length=1)

3 =>

array

0 => string 'b' (length=1)

1 => string 'c' (length=1)

4 =>

array

0 => string 'b' (length=1)

1 => string 'd' (length=1)

5 =>

array

0 => string 'c' (length=1)

1 => string 'd' (length=1)

要列出数组的所有子集,使用此组合算法只需执行

$base =array("a","b","c","d");

for($i = 1; $i<=4 ;$i++){

$comb = getCombinations($base,$i);

foreach($comb as $c){

echo implode(",",$c)."
";

}

}

输出是

a

b

c

d

a,b

a,c

a,d

b,c

b,d

c,d

a,b,c

a,b,d

a,c,d

b,c,d

a,b,c,d

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值