每次使用所有单词的PHP组合

每次使用所有单词的PHP组合,php,arrays,string,combinations,Php,Arrays,String,Combinations,这是我在这个网站上的第一个问题,所以我希望我能详细地回答这个问题 我需要将一个文本字符串转换为多个数组,其中包含文本字符串中“单词”和“单词短语”的所有不同组合 所以字符串应该是这样的: “2013年法国足球赛” 从中,我需要以下数组: array( 0 => array( 'Football', 'match', 'France', '2013' ), 1 => array( 'Football', 'match', 'Fra

这是我在这个网站上的第一个问题,所以我希望我能详细地回答这个问题

我需要将一个文本字符串转换为多个数组,其中包含文本字符串中“单词”和“单词短语”的所有不同组合

所以字符串应该是这样的: “2013年法国足球赛”

从中,我需要以下数组:

array(
0 => array(
    'Football',
    'match',
    'France',
    '2013'
),
1 => array(
    'Football',
    'match',
    'France 2013'
),
2 => array(
    'Football',
    'match France',
    '2013'
),
3 => array(
    'Football',
    'match France 2013'
),
4 => array(
    'Football match',
    'France',
    '2013'
),
5 => array(
    'Football match',
    'France 2013',
),
6 => array(
    'Football match France',
    '2013'
),
7 => array(
    'Football match France 2013',
),
)


因此,每个结果字符串可能由1到n个连续单词组成,并且每个子数组总共应包含每个单词一次的限制。

以下是一些有效的代码

<?php 

$str = 'Football match France 2013'; // Initialize sentence
$words = explode(" ",$str); // Break sentence into words
$p = array(array(array_shift($words))); // Load first word into permutation that has nothing to connect to

foreach($words as $word) { // for each remaining word
    $a = $p; // copy existing permutation for not-connected set
    $b = $p;  // copy existing permutation for connected set
    $s = count($p); // cache number of items in permutation
    $p = array(); // reset permutation (attempt to force garbage collection before adding words)
    for($i=0;$i<$s;$i++) { // loop through each item
       $a[$i][] = $word; // add word (not-connected)
       $b[$i][count($b[$i])-1] .= " ".$word; // add word (connected)
    }
    $p = array_merge($a,$b); // create permutation result by joining connected and not-connected sets
}

// Dump the array
print_r($p);

?>


那么,你尝试了什么?这是你的家庭作业,还是你真的需要它?谢谢!这是一个排列问题,每个单词可以连接到前面的单词,也可以不连接到前面的单词。奇点情况(第一个字)需要预加载到缓冲区中,因为它没有任何连接。然后在添加每个字时,它会使数组的大小加倍,因为只有两种可能的状态(已连接、未连接)。所有新词已连接的现有成员,以及所有新词未连接的现有成员。nl-x我添加了一些注释,使算法更容易理解。@RalphRitoch你想杀死nl-x吗?