My LeetCode Diary - Day28 BackTracking
491. Non-decreasing Subsequences
Link
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backTrack(nums,0);
return res;
}
void backTrack(int[] nums,int index) {
if (path.size() > 1) {
res.add(new ArrayList<>(path));
}
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = index; i < nums.length; i++) {
if ( !path.isEmpty() && nums[i] < path.getLast()) {
continue;
}
if (map.getOrDefault(nums[i],0) >= 1) {
continue;
}
path.add(nums[i]);
map.put(nums[i], map.getOrDefault(nums[i],0)+1);
backTrack(nums,i+1);
path.removeLast();
}
}
}
46. Permutations
Link
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
boolean[] used;
public List<List<Integer>> permute(int[] nums) {
used = new boolean[nums.length];
backTrack(nums);
return res;
}
void backTrack(int[] nums) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
path.add(nums[i]);
used[i] = true;
backTrack(nums);
used[i] = false;
path.removeLast();
}
}
}
47. Permutations II
Link
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
boolean[] used;
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
used= new boolean[nums.length];
backTrack(nums);
return res;
}
void backTrack(int[] nums) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
if (i > 0 && nums[i] == nums[i-1] && used[i-1]==false) {
continue;
}
path.add(nums[i]);
used[i] = true;
backTrack(nums);
path.removeLast();
used[i] = false;
}
}
}