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


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

查看所有标签

猜你喜欢:

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

Introduction to Graph Theory

Introduction to Graph Theory

Douglas B. West / Prentice Hall / 2000-9-1 / USD 140.00

For undergraduate or graduate courses in Graph Theory in departments of mathematics or computer science. This text offers a comprehensive and coherent introduction to the fundamental topics of graph ......一起来看看 《Introduction to Graph Theory》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具