内容简介:递归第6天
2 0 1 9 -6-11 星 期二 开 始 吧
递归第6天
上 一 题 链 接 Leetcode基础刷题之 PHP 解析(46. Permutations)
题 目 描 述
全排列第二版,这一版是给定数组中可能会出现相同的值,但是在结果中不能出现重复的排列。
题 目 分 析
为了避免当次排列中数被重复使用,我们还是使用 visited标记, 因为可能出现相同的值,但是又不能出现相同的排列,这里先把数组进行排序,然后递归中再设置一个条件,当前的数和他上一个数相等并且上一个数visited等于0的情况下说明此次已经是重复排列,退出。visited等于0并不是说前一个还没有被标记访问过,而是由于递归结束之后把当次排列当前下标 visited重置为0。每一轮结束都需要重置为0,代表新一轮的排列。
/**
* @param Integer[] $nums
* @return Integer[][]
*/
function permuteUnique($nums) {
sort($nums);
$res=[];
$out=[];
$visitied=[];
$this->helper($nums,0,$visitied,$out,$res);
return $res;
}
function helper($nums,$index,&$visitied,&$out,&$res)
{
if($index==count($nums)){
array_push($res,$out);
return ;
}
for($j=0;$j<count($nums);$j++){
if($visitied[$j]==1) continue;
if($j>0 && $nums[$j]==$nums[$j-1] && $visitied[$j-1]==0) continue;
$visitied[$j]=1;
array_push($out,$nums[$j]);
$this->helper($nums,$index+1,$visitied,$out,$res);
array_pop($out);
$visitied[$j]=0;
}
}
Github整理地址 : https://github.com/wuqinqiang/leetcode-php
以上所述就是小编给大家介绍的《Leetcode基础刷题之PHP解析(47. Permutations II)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Seasoned Schemer
Daniel P. Friedman、Matthias Felleisen / The MIT Press / 1995-12-21 / USD 38.00
drawings by Duane Bibbyforeword and afterword by Guy L. Steele Jr.The notion that "thinking about computing is one of the most exciting things the human mind can do" sets both The Little Schemer (form......一起来看看 《The Seasoned Schemer》 这本书的介绍吧!