[LeetCode 46/47]PHP 回溯算法求解全排列
码农天地 -原文链接: 何晓东 博客
全排列给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
解题思路直接参考 回溯算法团灭排列/组合/子集问题
代码
class Solution {
public $res = [];
/**
* @param Integer[] $nums
* @return Integer[][]
*/
function permute($nums) {
$this->dfs([], $nums);
return $this->res;
}
function dfs($array, $candidates) {
if (count($array) === count($candidates)) {
$this->res[] = $array;
return;
}
for ($i = 0; $i < count($candidates); $i++) {
if (in_array($candidates[$i], $array)) continue;
$array[] = $candidates[$i];
$this->dfs($array, $candidates);
array_pop($array);
}
}
}
额外:LeetCode 47 全排列 Ⅱ,区别是 第一:加了一个sort,排序之后只有相邻元素才会相同 第二:判断去重条件,加了是否访问过的判断
class Solution {
public $res = [];
/**
* @param Integer[] $nums
* @return Integer[][]
*/
function permuteUnique($nums) {
sort($nums);
$this->dfs([], $nums, []);
return $this->res;
}
function dfs($array, $candidates, $visited) {
if (count($array) === count($candidates)) {
$this->res[] = $array;
return;
}
for ($i = 0; $i < count($candidates); $i++) {
if ($visited[$i]) continue;
if ($i > 0 && $candidates[$i] == $candidates[$i -1] && $visited[$i - 1]) continue;
$array[] = $candidates[$i];
$visited[$i] = 1;
$this->dfs($array, $candidates, $visited);
array_pop($array);
$visited[$i] = 0;
}
}
}
参考链接
回溯算法团灭排列/组合/子集问题最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。
php介绍
PHP即“超文本预处理器”,是一种通用开源脚本语言。PHP是在服务器端执行的脚本语言,与C语言类似,是常用的网站编程语言。PHP独特的语法混合了C、Java、Perl以及 PHP 自创的语法。利于学习,使用广泛,主要适用于Web开发领域。
Tags 标签
phpleetcode扩展阅读
隐藏apache版本信息
2018-09-29 22:56:15 []CentOS 6.5安装php5.6
2018-09-29 23:36:53 []PHP版ZIP压缩解压类库
2018-12-22 00:11:00 []CentOS7.2安装 PHP7.3.4 操作详细教程
2020-06-28 07:09:43 []PHP 设置脚本超时时间、PHP脚本内存限制设置
2020-06-28 07:09:43 []PHP 函数filesize获取文件大小错误,一直不变
2020-06-28 07:09:43 []Linux php: command not found
2020-02-04 12:30:13 []php 缓冲区 buffer 原理
2020-06-28 07:09:43 []PHP中三种设置脚本最大执行时间的方法
2020-06-28 07:17:34 []加个好友,技术交流
