package leetcode; import java.util.ArrayList; import java.util.List; public class demo_46 { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> list=new ArrayList<List<Integer>>(); //设置数组记录当前循环中该数字是否被访问 int[] visited=new int[nums.length]; for(int i=0;i<nums.length;i++) { visited[i]=0; } backtrack(list,nums,new ArrayList<Integer>(),visited); System.out.println(list); return list; } public void backtrack(List<List<Integer>> list,int[] nums,List<Integer> alist,int[] visited) { if(alist.size()==nums.length) { list.add(new ArrayList<Integer>(alist)); } else { for(int j=0;j<nums.length;j++) { //若当前数字已被访问则继续循环 if(visited[j]==1) {continue;} alist.add(nums[j]); visited[j]=1; backtrack(list, nums,alist,visited); alist.remove(alist.size()-1); visited[j]=0; } } } public static void main(String[] args) { // TODO Auto-generated method stub demo_46 d46 = new demo_46(); int[] nums= {1,2,3}; d46.permute(nums); } }