在PHP 中獲取所有可能的組合:綜合解決方案
從一維數組中檢索所有可能的組合可能是一項複雜的任務,尤其是考慮組合和排列。雖然解決這個問題有多種方法,但一種高效的解決方案涉及實現遞歸函數。
遞歸函數,深度_picker(),對數組執行深度優先搜索,探索所有分支並組合元素以形成組合。它維護一個臨時字串,該字串會隨著每個元素的變化而逐漸修改,而收集數組則儲存最終的組合。讓我們看看這個函數是如何運作的:
實現和執行
要實現這種深度優先搜尋和組合檢索,可以使用以下PHP 代碼:
0) {
depth_picker($arrcopy, $temp_string ." " . $elem[0], $collect);
} else {
$collect []= $temp_string. " " . $elem[0];
}
}
}
$collect = array();
depth_picker($array, "", $collect);
print_r($collect);
?>
執行後,此程式碼輸出以下所有可能組合和排列的陣列:
Array ( [0] => Alpha [1] => Alpha Beta [2] => Alpha Beta Gamma [3] => Alpha Beta Gamma Sigma [4] => Alpha Beta Sigma [5] => Alpha Beta Sigma Gamma [6] => Alpha Gamma [7] => Alpha Gamma Beta [8] => Alpha Gamma Beta Sigma [9] => Alpha Gamma Sigma [10] => Alpha Gamma Sigma Beta [11] => Alpha Sigma [12] => Alpha Sigma Beta [13] => Alpha Sigma Beta Gamma [14] => Alpha Sigma Gamma [15] => Alpha Sigma Gamma Beta [16] => Beta [17] => Beta Alpha [18] => Beta Alpha Gamma [19] => Beta Alpha Gamma Sigma [20] => Beta Alpha Sigma [21] => Beta Alpha Sigma Gamma [22] => Beta Gamma [23] => Beta Gamma Alpha [24] => Beta Gamma Alpha Sigma [25] => Beta Gamma Sigma [26] => Beta Gamma Sigma Alpha [27] => Beta Sigma [28] => Beta Sigma Alpha [29] => Beta Sigma Alpha Gamma [30] => Beta Sigma Gamma [31] => Beta Sigma Gamma Alpha [32] => Gamma [33] => Gamma Alpha [34] => Gamma Alpha Beta [35] => Gamma Alpha Beta Sigma [36] => Gamma Alpha Sigma [37] => Gamma Alpha Sigma Beta [38] => Gamma Beta [39] => Gamma Beta Alpha [40] => Gamma Beta Alpha Sigma [41] => Gamma Beta Sigma [42] => Gamma Beta Sigma Alpha [43] => Gamma Sigma [44] => Gamma Sigma Alpha [45] => Gamma Sigma Alpha Beta [46] => Gamma Sigma Beta [47] => Gamma Sigma Beta Alpha [48] => Sigma [49] => Sigma Alpha [50] => Sigma Alpha Beta [51] => Sigma Alpha Beta Gamma [52] => Sigma Alpha Gamma [53] => Sigma Alpha Gamma Beta [54] => Sigma Beta [55] => Sigma Beta Alpha [56] => Sigma Beta Alpha Gamma [57] => Sigma Beta Gamma [58] => Sigma Beta Gamma Alpha [59] => Sigma Gamma [60] => Sigma Gamma Alpha [61] => Sigma Gamma Alpha Beta [62] => Sigma Gamma Beta [63] => Sigma Gamma Beta Alpha )
此方法提供了一種全面且高效的解決方案,用於獲取數組中元素的所有可能組合,確保輸出中包含組合和不同的排列。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3