Leetcode基础刷题之PHP解析(77. Combinations)

栏目: PHP · 发布时间: 6年前

2 0 1 9 -6-12   期三  

Leetcode基础刷题之 PHP 解析(47. Permutations II)

Leetcode基础刷题之PHP解析(77. Combinations)

给定两个整型数字n和k,返回1到n的k个数所有组合情况。

还是和之前的题目一样,定义了两个数组,一个存储单次的组合,一个存储最后的所有组合,那么每次当前组合中的个数等于k的时候,就把当前小组合push到大组合中,否则的话继续递归。

/**
     * @param Integer $n
     * @param Integer $k
     * @return Integer[][]
     */
    function combine($n, $k) {
        $res=[];
        $out=[];
        $this->helper($n,$k,1,$out,$res);
        return $res;
    }
    
    function helper($n,$k,$level,&$out,&$res){
       
        if(count($out)==$k){
            array_push($res,$out);
            return ;
        }
        for($i=$level;$i<=$n;$i++){
            array_push($out,$i);
            $this->helper($n,$k,$i+1,$out,$res);
            array_pop($out);
        }
    }

Github整理地址 : https://github.com/wuqinqiang/leetcode-php


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beginning PHP and MySQL 5

Beginning PHP and MySQL 5

W. Jason Gilmore / Apress / 2006-01-23 / USD 44.99

Beginning PHP and MySQL 5: From Novice to Professional, Second Edition offers comprehensive information about two of the most prominent open source technologies on the planet: the PHP scripting langua......一起来看看 《Beginning PHP and MySQL 5》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具