Leetcode基础刷题之PHP解析(77. Combinations)
2019-6-12 星期三 开始吧
上一题链接Leetcode基础刷题之PHP解析(47. Permutations II)

题目描述
给定两个整型数字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
No Comments