Given a collection of distinct numbers, return all possible permutations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
class { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> list=new ArrayList<>(); backTrack(list,new LinkedList<>(),nums); return list; } public void backTrack(List<List<Integer>> list,LinkedList <Integer> tempList,int [] nums) { if(tempList.size()==nums.length) { list.add(new ArrayList<>(tempList)); } else { for(int i=0;i<nums.length;i++) { if(tempList.contains(nums[i])) continue; tempList.add(nums[i]); backTrack(list,tempList,nums); tempList.removeLast(); } } } }
|
TIPS:
递归
近期评论