layout: posttitle: PHP 回溯算法求解全排列
subtitle: PHP 回溯算法求解全排列
date: 2020-09-18
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Go
- PHP
- LeetCode 46 47
- 回溯算法
- 全排列

全排列

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

示例:

  1. 输入: [1,2,3]
  2. 输出:
  3. [
  4. [1,2,3],
  5. [1,3,2],
  6. [2,1,3],
  7. [2,3,1],
  8. [3,1,2],
  9. [3,2,1]
  10. ]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations

解题思路

直接参考 回溯算法团灭排列/组合/子集问题

代码
  1. class Solution {
  2. public $res = [];
  3. /**
  4. * @param Integer[] $nums
  5. * @return Integer[][]
  6. */
  7. function permute($nums) {
  8. $this->dfs([], $nums);
  9. return $this->res;
  10. }
  11. function dfs($array, $candidates) {
  12. if (count($array) === count($candidates)) {
  13. $this->res[] = $array;
  14. return;
  15. }
  16. for ($i = 0; $i < count($candidates); $i++) {
  17. if (in_array($candidates[$i], $array)) continue;
  18. $array[] = $candidates[$i];
  19. $this->dfs($array, $candidates);
  20. array_pop($array);
  21. }
  22. }
  23. }

额外:LeetCode 47 全排列 Ⅱ,区别是 第一:加了一个sort,排序之后只有相邻元素才会相同 第二:判断去重条件,加了是否访问过的判断

  1. class Solution {
  2. public $res = [];
  3. /**
  4. * @param Integer[] $nums
  5. * @return Integer[][]
  6. */
  7. function permuteUnique($nums) {
  8. sort($nums);
  9. $this->dfs([], $nums, []);
  10. return $this->res;
  11. }
  12. function dfs($array, $candidates, $visited) {
  13. if (count($array) === count($candidates)) {
  14. $this->res[] = $array;
  15. return;
  16. }
  17. for ($i = 0; $i < count($candidates); $i++) {
  18. if ($visited[$i]) continue;
  19. if ($i > 0 && $candidates[$i] == $candidates[$i -1] && $visited[$i - 1]) continue;
  20. $array[] = $candidates[$i];
  21. $visited[$i] = 1;
  22. $this->dfs($array, $candidates, $visited);
  23. array_pop($array);
  24. $visited[$i] = 0;
  25. }
  26. }
  27. }

参考链接

  1. 回溯算法团灭排列/组合/子集问题

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券