Skip to content

Latest commit

 

History

History
58 lines (47 loc) · 2.04 KB

46.md

File metadata and controls

58 lines (47 loc) · 2.04 KB

✏️Leetcode之PHP版题目解析(46. Permutations)

2019-06-07 吴亲库里 库里的深夜食堂


✏️描述

给定一组数字,求出所有的排列情况


✏️题目实例

****

✏️题目分析

这道题和之前的两题大体思路都是一样的,整体的思路和前两题是一样的,只要修改对应的条件即可。因为这里每个数字在每一个排列中不能被重复利用,我们需要标识一下当前排列的中的遍历的数是否已经在排列当中了。$index用来标识访问的数组下标,一但当前的下标等于数组的总数,说明此时这轮排列结束,把当前排列的值push到最终返回的二维数组中。

✏️解法一

        /**
            * @param Integer[] $nums
            * @return Integer[][]
            */
           function permute($nums) {
               $out=[];
               $res=[];
               $visited=[];
               $this->helper($nums,0,$visited,$out,$res);
               return $res;
           }
           
           function helper($nums,$index,&$visited,&$out,&$res)
           {
               if($index==count($nums)){
                   array_push($res,$out);
                   return;
               } 
               
               for($j=0;$j<count($nums);$j++){
                   if($visited[$j]==1) continue;
                   $visited[$j]=1;
                   array_push($out,$nums[$j]);
                   $this->helper($nums,$index+1,$visited,$out,$res);
                   array_pop($out);
                   $visited[$j]=0;
               }
               
           }

联系