PHP uses recursion to generate subarrays (code example)

藏色散人
Release: 2023-04-05 17:00:01
Original
2616 people have browsed it

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]
Copy after login

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);
Copy after login

Output:

[1]
[1,2]
[2]
[1,2,3]
[2,3]
[3]
Copy after login

Time complexity Properties: PHP uses recursion to generate subarrays (code example)

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template