Home > Article > Backend Development > PHP uses recursion to generate subarrays (code example)
Given an array, use recursion to generate all possible subarrays of the given array. This article will introduce to you how to use PHP to implement this function.
Example:
输入:[1,2,3] 输出:[1],[1,2],[2],[1,2,3],[2,3],[3] 输入:[1,2] 输出:[1],[1,2],[2]
Method:
We use two pointers start and end to maintain the start and end point of the array and as given below Step operation:
1. If we have reached the end of the array, stop
2. If start is greater than end, increase the end index
3. Start from the index Print the subarray to end and increment the starting index
The following is an example of PHP code implementation of the above method:
<?php // 使用递归函数为给定数组打印所有可能的子数组 function printSubArrays($arr, $start, $end) { // 如果我们已经到达数组的末尾,就停止 if ($end == count($arr)) return; // 增加端点并从0开始 else if ($start > $end) return printSubArrays($arr, 0, $end + 1); // 打印子数组并增加起始点 else { echo "["; for($i = $start; $i < $end + 1; $i++) { echo $arr[$i]; if($i != $end) echo ", "; } echo "]\n"; return printSubArrays($arr, $start + 1, $end); } } $arr = array(1, 2, 3); printSubArrays($arr, 0, 0);
Output:
[1] [1,2] [2] [1,2,3] [2,3] [3]
Time complexity Properties:
Related recommendations: "PHP Tutorial"
This article is an introduction to the method of using recursion to generate subarrays in PHP. I hope it will be helpful to friends who need it. Helps!
The above is the detailed content of PHP uses recursion to generate subarrays (code example). For more information, please follow other related articles on the PHP Chinese website!