当前位置: 首页 > 后端技术 > PHP

[LeetCode46-47]PHP回溯算法求解满排列

时间:2023-03-29 14:49:06 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...解题思路直接参考了回溯算法群湮灭排列/组合/subset问题代码类解决方案{public$res=[];/***@paramInteger[]$nums*@returnInteger[][]*/functionpermute($nums){$this->dfs([],$nums);返回$this->res;}functiondfs($array,$candidates){if(count($array)===count($candidates)){$this->res[]=$array;返回;}for($i=0;$idfs($array,$candidates);array_pop($数组);}}}Extra:LeetCode47全排二,区别第一:加一个排序,排序后只有相邻的元素相同第二:判断去重条件,加入是否被访问过的判断classSolution{公共$res=[];/***@paramInteger[]$nums*@returnInteger[][]*/functionpermuteUnique($nums){sort($nums);$this->dfs([],$nums,[]);返回$this->res;}functiondfs($array,$candidates,$visited){if(count($array)===count($candidates)){$this->res[]=$array;返回;}for($i=0;$i0&&$candidates[$i]==$candidates[$i-1]&&$visited[$i-1])继续;$array[]=$candidates[$i];$访问[$i]=1;$this->dfs($array,$candidates,$visited);array_pop($数组);$访问[$i]=0;}}}参考链接回溯算法组淘汰排列/组合/子集问题最后,就吃阿里云全系列产品/短信套餐特购中小企业上云最佳选择阿里云内部优惠券