1.题目描述
Given a collection of distinct integers, return all possible permutations.
给定一个没有重复数字的序列,返回其所有可能的全排列。
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
2.Solutions
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 27 28 29 30 31 32 33
|
public static List<List<Integer>> permute(int[] nums) { List<List<Integer>> list = new ArrayList<>(); backtrack(list, new ArrayList<Integer>(), nums); return list; }
private static void (List<List<Integer>> list, List<Integer> tempList, int[] nums) { printList(tempList); 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.remove(tempList.size() - 1); } } }
private static void printList(List<Integer> list) { if (list.size() == 0){ return; } for (Integer integer : list) { System.out.print(integer); } System.out.println(); }
|
(完)
近期评论