public class T1_12_2021 {
//全排列问题
public static int num[]=new int [] {1,2,3,4,5,6};//待排数组
public static ArrayList<Integer> pathList=new ArrayList<Integer>();//存储每次答案的路径
public static List<List<Integer>> res=new ArrayList<>();//存储答案
public static void dfs()
{
//当所有元素都被加入到pathList中,本次递归终止
if(pathList.size()==num.length)
{
ArrayList<Integer> temp=new ArrayList<Integer>();
for(int i=0;i<num.length;i++)
{
temp.add(pathList.get(i));
}
res.add(temp);//把答案加入到答案集合中
return ;
}
for(int i=0;i<num.length;i++)
{
if(pathList.contains(num[i])==true)//如果当前元素已经被选择过了,那么跳过
continue;
//如果当前元素没有被选择,那么选择当前元素
pathList.add(num[i]);
//递归到下一层
dfs();
pathList.remove(pathList.size()-1);
}
}
public static void main(String args[])
{
dfs();
for(int i=0;i<res.size();i++)
{
for(int j=0;j<res.get(i).size();j++)
{
System.out.print(" "+res.get(i).get(j));
}
System.out.println();
}
}
}
全排列问题之java实现
最新推荐文章于 2026-07-24 23:13:08 发布

278

被折叠的 条评论
为什么被折叠?



