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

栏目: 编程工具 · 发布时间: 6年前

2 0 1 9 -6-10   期一 

上半年的假终于全剧终了,人一懒惰起来,再调整状态就困难多了

Leetcode基础刷题之 PHP 解析(40. Combination Sum II)

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

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

这道题和之前的两题大体思路都是一样的,整体的思路和前两题是一样的,只要修改对应的条件即可。因为这里每个数字在每一个排列中不能被重复利用,我们需要标识一下当前排列的中的遍历的数是否已经在排列当中了。 $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;
        }
        
    }

Github整理地址 : https://github.com/wuqinqiang/leetcode-php


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

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

PHP and MySQL for Dynamic Web Sites : Visual QuickPro Guide

PHP and MySQL for Dynamic Web Sites : Visual QuickPro Guide

Larry Ullman / Peachpit Press / 2005 / USD 39.99

It hasn't taken Web developers long to discover that when it comes to creating dynamic, database-driven Web sites, MySQL and PHP provide a winning open source combination. Add this book to the mix, an......一起来看看 《PHP and MySQL for Dynamic Web Sites : Visual QuickPro Guide》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

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

RGB CMYK 互转工具