Leetcode 47. Permutations II
2017-01-05 11:44
393 查看
public class Solution {
public static void backTrack(int[] nums, boolean[] used, List<Integer> tmp, List<List<Integer>> res) {
if (tmp.size() == nums.length) {
res.add(new ArrayList<>(tmp));
return;
}
else {
for (int i=0; i<nums.length; i++) {
if (used[i] || i>0 && nums[i-1]==nums[i] && !used[i-1]) continue;
used[i] = true;
tmp.add(nums[i]);
backTrack(nums, used, tmp, res);
used[i] = false;
tmp.remove(tmp.size()-1);
}
}
}
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums); // always sort when there are duplicates in the array
List<List<Integer>> res = new ArrayList<>();
backTrack(nums, new boolean[nums.length], new ArrayList<>(), res);
return res;
}
}
public static void backTrack(int[] nums, boolean[] used, List<Integer> tmp, List<List<Integer>> res) {
if (tmp.size() == nums.length) {
res.add(new ArrayList<>(tmp));
return;
}
else {
for (int i=0; i<nums.length; i++) {
if (used[i] || i>0 && nums[i-1]==nums[i] && !used[i-1]) continue;
used[i] = true;
tmp.add(nums[i]);
backTrack(nums, used, tmp, res);
used[i] = false;
tmp.remove(tmp.size()-1);
}
}
}
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums); // always sort when there are duplicates in the array
List<List<Integer>> res = new ArrayList<>();
backTrack(nums, new boolean[nums.length], new ArrayList<>(), res);
return res;
}
}
相关文章推荐
- LeetCode 46 Permutations + LeetCode 47 Permutations II
- 【leetcode】【47】Permutations II
- [LeetCode]47 Permutations II
- [leetcode 47] Permutations II
- LeetCode 47 Permutations II(全排列)
- [leetCode刷题笔记]47. Permutations II
- LeetCode--47. Permutations II
- LeetCode47:Permutations II
- LeetCode 47. Permutations II
- LeetCode 47. Permutations II
- (Java)LeetCode-47. Permutations II
- [Leetcode] 47. Permutations II
- Leetcode-47. Permutations II
- Leetcode 47. Permutations II
- leetcode-47-Permutations II 搜索-剪枝
- LeetCode-----46.Permutations&&47.Permutations II (全排列----回溯法)
- LeetCode(47)Permutations II
- Leetcode 46. Permutations & 47. Permutations II
- LeetCode --- 47. Permutations II
- [Leetcode] 47. Permutations II