class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums.length == 0) return result;
if (nums.length == 1) {
List<Integer> l = new LinkedList<>();
l.add(nums[0]);
result.add(l);
return result;
}
for(int i=0; i<nums.length; ++i) {
int[] tmp = new int[nums.length-1];
if (i>0) {
System.arraycopy(nums, 0, tmp, 0, i);
}
if (i<nums.length-1) {
System.arraycopy(nums, i+1, tmp, i, nums.length-1-i);
}
List<List<Integer>> r = permute(tmp);
for(List<Integer> l: r) {
l.add(0, nums[i]);
}
result.addAll(r);
}
return result;
}
}
如果輸入數組參數中有重複元素,並且結果中要求去除重複排列,可在循環中用set記錄下已處理過的元素。
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums.length == 0) return result;
if (nums.length == 1) {
List<Integer> l = new LinkedList<>();
l.add(nums[0]);
result.add(l);
return result;
}
Set<Integer> set = new HashSet<>();
for(int i=0; i<nums.length; ++i) {
if (set.contains(nums[i])) continue; //已處理過,skip
int[] tmp = new int[nums.length-1];
if (i>0) {
System.arraycopy(nums, 0, tmp, 0, i);
}
if (i<nums.length-1) {
System.arraycopy(nums, i+1, tmp, i, nums.length-1-i);
}
List<List<Integer>> r = permuteUnique(tmp);
for(List<Integer> l: r) {
l.add(0, nums[i]);
}
result.addAll(r);
set.add(nums[i]);
}
return result;
}
}