再上一题的基础上做一点改动,就是判断是不是已经有了。不过时间3084ms,略慢
class Solution {
/**
* @param nums: A list of integers.
* @return: A list of unique permutations.
*/
public List<List<Integer>> permuteUnique(int[] nums) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
List<Integer> item = new ArrayList<>();
if (nums == null || nums.length == 0) {
result.add(item);
return result;
}
int[] book = new int[nums.length];
dfs(nums, book, 0, item, result);
return result;
}
public void dfs(int[] nums, int[] book, int step, List<Integer> item, List<List<Integer>> result) {
if (step == book.length) {
//修改了一下这里
if (!result.contains(item)) {
result.add(new ArrayList<>(item));
}
return;
}
for (int i = 0; i < book.length; i++) {
if (book[i] == 0) {
book[i] = 1;
item.add(nums[i]);
dfs(nums, book, step + 1, item, result);
item.remove(item.size() - 1);
book[i] = 0;
}
}
}
}
2.九章
在执行的过程中去重,时间比我之前的快 2634ms
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
ArrayList<List<Integer>> results = new ArrayList<List<Integer>>();
if (nums == null) {
return results;
}
if(nums.length == 0) {
results.add(new ArrayList<Integer>());
return results;
}
Arrays.sort(nums);
ArrayList<Integer> list = new ArrayList<Integer>();
int[] visited = new int[nums.length];
for ( int i = 0; i < visited.length; i++){
visited[i] = 0;
}
helper(results, list, visited, nums);
return results;
}
public void helper(ArrayList<List<Integer>> results,
ArrayList<Integer> list, int[] visited, int[] nums) {
if(list.size() == nums.length) {
results.add(new ArrayList<Integer>(list));
return;
}
for(int i = 0; i < nums.length; i++) {
if ( visited[i] == 1 || ( i != 0 && nums[i] == nums[i - 1]
&& visited[i-1] == 0)){
continue;
}
visited[i] = 1;
list.add(nums[i]);
helper(results, list, visited, nums);
list.remove(list.size() - 1);
visited[i] = 0;
}
}
}
3.根据九章思路优化
2666ms
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
List<Integer> item = new ArrayList<>();
if (nums == null || nums.length == 0) {
result.add(item);
return result;
}
int[] book = new int[nums.length];
Arrays.sort(nums);
dfs(nums, book, 0, item, result);
return result;
}
public void dfs(int[] nums, int[] book, int step, List<Integer> item, List<List<Integer>> result) {
if (step == book.length) {
//修改
result.add(new ArrayList<>(item));
return;
}
for (int i = 0; i < book.length; i++) {
//修改
if (i != 0) {
if (nums[i] == nums[i - 1] && book[i - 1] == 1) {
//book[i]=1;这里可以不加这一句,因为,,无论无何都是访问不到book[i]的值的
continue;
}
}
if (book[i] == 0) {
book[i] = 1;
item.add(nums[i]);
dfs(nums, book, step + 1, item, result);
item.remove(item.size() - 1);
book[i] = 0;
}
}
}
}