Permutations II Leetcode Solution in java | Hindi Coding Community

0

 


Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.


Example 1:

Input: nums = [1,1,2]

Output:

[[1,1,2],

 [1,2,1],

 [2,1,1]]




public class Solution {
public List<List<Integer>> permuteUnique(int[] num) {
LinkedList<List<Integer>> res = new LinkedList<>();
res.add(new ArrayList<>());
for (int i = 0; i < num.length; i++) {
Set<String> cache = new HashSet<>();
while (res.peekFirst().size() == i) {
List<Integer> l = res.removeFirst();
for (int j = 0; j <= l.size(); j++) {
List<Integer> newL = new ArrayList<>(l.subList(0,j));
newL.add(num[i]);
newL.addAll(l.subList(j,l.size()));
if (cache.add(newL.toString())) res.add(newL);
}
}
}
return res;
}
}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !