Algorithm to get all possible string combinations from array up to certain length

后端 未结 12 936
攒了一身酷
攒了一身酷 2020-12-01 02:22

What is the best algorithm to get all possible string combinations from a given array with a minimum & maximum length value.

Note: This adds complexity since the

12条回答
  •  攒了一身酷
    2020-12-01 03:01

    Accumulative set product for k times with a set S which is empty initially will produce all permutations up to k-long, with n = |S| ..

    Time: O(kn^2)

    Space: O(kn^2)

    // Enumerate all permutations, PHP
    // by Khaled A Khunaifer, 25/3/2013
    
    function setProduct($a, $b)
    {
        $arr = array();
    
        foreach ($a as $s)
        {
            foreach ($b as $t)
            {
                $arr[] = $s . $t;
            }
        }
    
        return $arr;
    }
    
    function enumerate ($arrary, $maxLen)
    {
        $enumeration = array();
    
        for (var $i = 1; $i <= $maxLen; $i++)
        {
            $enumeration += setProduct($enumeration, $array);
        }
    }
    

提交回复
热议问题