题目:
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
解题思路:
回溯法,注意同一个元素不能重复选取。
代码实现:
class Solution { public List<List<Integer>> permute(int[] nums) { int scale = 0, maxScale = nums.length; List<List<Integer>> result = new LinkedList<List<Integer>>(); int[] index = new int[maxScale]; Arrays.fill(index, -1); while (scale >= 0) { if (scale == maxScale) { List<Integer> solution = new LinkedList<Integer>(); for (int i = 0; i < maxScale; i ++) { solution.add(nums[index[i]]); } result.add(solution); scale --; } index[scale] ++; if (check(index, scale)) { scale ++; } else { if (index[scale] >= maxScale) { index[scale] = -1; scale--; } } } return result; } private boolean check(int[] check, int scale) { int k = check[scale]; if (k >= check.length) return false; if (scale == 0) return true; for (int i = 0; i < scale; i ++) { if (check[i] == k) return false; } return true; } }