2017-02-19 69 views

回答

0

您將基本上從開始到數組中結束在開始時放置當前數字,然後將數組的所有排列附加到數組中,而不將開始時的數字添加到數組中。如果你使用遞歸,那很簡單。 例子:

input: [1] [2] [3] 

step 1: [1] [unknown] [unknown] 

現在調用該函數生成所有排列(此功能)和追加你得到的到的陣列。

每次函數調用所需的迭代次數爲n!(n)*(n-1)*(n-2) ...

0

有一段時間,我有一個類似的問題,我爲我的日常工作(這不是程序員)做了些什麼。我發現了以下代碼的JavaScript版本。希望我已經對它進行了足夠的代碼轉換。我的評論。如果你可以等待一會兒(即將休假),那麼我可以研究如何限制遞歸調用,使其減少資源佔用。

<?php 

function combinations($arr){ 
    $result = array(); 
    //the result array, returned by this outer function. 
    function fn($active, $rest, &$a){ 
     if(!$active && !$rest) 
      return;//If we have empty arrays, stoppit 
     if(!$rest){ 
      //Are we out of remaining options? Yep, add the active array. 
      $a[] = $active; 
     }else{ 
      /* 
       we are currently splitting the work between the two options. First is that we compute the 
       combinations of the currently $active and the $rest array offset by 1. 
      */ 
      fn($active, array_slice($rest,1), $a); 
      $active[] = $rest[0]; 
      //Next we add in the first element of the rest array to the active array, and slice off that new element to avoid duplicates. 
      fn($active, array_slice($rest,1), $a); 

     } 
    } //Function that actually does the work; 
    fn([],$arr,$result); 
    return $result; 
} 

$combos = combinations([1,2,3,4,5]); 
$combos = array_filter($combos,function($item){ 
    return count($item) == 2; 
}); 

print_r($combos); 

?> 
相關問題