3

我需要获得一个字符串的渐进式单词组合。

例如“this is string” 输出:“this is string” “this is” “this string” “is string” “this” “is” “string”

你知道类似的算法吗?(我需要 php 语言)谢谢 ;)

4

2 回答 2

4

这是您问题的简单代码解决方案。我将每个字符串递归地连接到数组中的其余字符串。

$string = "this is a string";  
$strings = explode(' ', $string);

// print result
print_r(concat($strings, ""));

// delivers result as array
function concat(array $array, $base_string) {

    $results = array();
    $count = count($array);
    $b = 0;
    foreach ($array as $key => $elem){
        $new_string = $base_string . " " . $elem;
        $results[] = $new_string;
        $new_array = $array;

        unset($new_array[$key]);

        $results = array_merge($results, concat ($new_array, $new_string));

    }
    return $results;
}
于 2011-02-21T12:41:39.683 回答
1

看看例如。http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations用于算法描述。

于 2011-02-21T11:19:09.230 回答