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


2019-6-12 期三 

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

275262c1780894ac3f43fe7bd87ead78.png

给定两个整型数字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


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode基础刷题之PHP解析(47. Permutations II)

>> 下一篇: Leetcode PHP题解--D85 242. Valid Anagram