利用递归求字符串的子序列(从左到右)

1.PHP实现

<?php
//获取字符串str 的子序列
//如 $str = 'abcdefg'; 其所有子序列为$str1='a',$str2='b',
//$str3='c' ...

//str固定不变,
//index此时来到的位置,要 or 不要
//如果index来到str中的终止位置,把沿途路径放入结果集中
//之前做出的选择就是path
//                     a
//            1       / \     0
//                   b   b
//            1     / \ / \   0
//                 c  c c  c
//            1   / \/ \/\ /\ 0
//               d  dd dd dd d
//                   ...
//       字序列个数 2^(n-1),n为字符串的长度
function getSubSequeuece($arrChar=[],$index=0,$path,&$result)
{
    $num = count($arrChar);
    if($num==0)
       return;
    if($num == ($index+1)){
       $result[] = $path;
       return;
    }
    //通过某个节点
    $string = $path.$arrChar[$index];
    $index++;
    getSubSequeuece($arrChar,$index,$string,$result);
    //不通过某个节点
    $string2 = $path;
    getSubSequeuece($arrChar,$index,$string2,$result);

}

$arrChar=['H','e','l','l','o',',','W','o','r','l','d','!'];
$result=[];
getSubSequeuece($arrChar,0,'',$result);

print_r($result);

 

posted @ 2021-02-08 11:10  不知起什么名字  阅读(151)  评论(0编辑  收藏  举报