您的位置:首页 > 文旅 > 美景 > day-45 全排列

day-45 全排列

2024/10/6 12:20:00 来源:https://blog.csdn.net/qq_53568730/article/details/141758665  浏览:    关键词:day-45 全排列

在这里插入图片描述
思路
递归调用dfs,利用一个数组来表示当前位置是否已经被选中,如果没有则选中当前数字,num+1(num表示已经选中数字个数),每当num==nums.length时,将List加入答案

解题过程
注意:使用num+1作为传参,不要num++(num++是先传参,再++)

Code

class Solution {public List<List<Integer>> list=new ArrayList<>();public int len;public int choose[];public List<List<Integer>> permute(int[] nums) {len=nums.length;choose=new int[len];Arrays.fill(choose,1);List<Integer> p=new ArrayList<>();dfs(p,0,nums);return list;}public void dfs(List<Integer> p,int num,int[] arr){if(num==len){list.add(new ArrayList(p));return;}for(int j=0;j<len;j++){if(choose[j]!=-1){choose[j]=-1;p.add(arr[j]);choose[j]=-1;dfs(p,num+1,arr);p.remove(p.size()-1);choose[j]=1;}}}
}作者:菜卷
链接:https://leetcode.cn/problems/permutations/solutions/2899311/quan-pai-lie-by-ashi-jian-chong-dan-liao-br1q/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com