2021.3.25
78. 子集
class Solution {
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
LinkedList<Integer> track = new LinkedList<>();
backtrack(nums, 0, track);
return res;
}
void backtrack(int[] nums, int start, LinkedList<Integer> track) {
res.add(new LinkedList<>(track));
for (int i = start; i < nums.length; i++) {
track.add(nums[i]);
backtrack(nums, i + 1, track);
track.removeLast();
}
}
}
77. 组合
class Solution {
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
if (k <= 0 || n <= 0) {
return res;
}
LinkedList<Integer> track = new LinkedList<>();
backtrack(n, k, 1, track);
return res;
}
void backtrack(int n, int k, int start, LinkedList<Integer> track) {
if (k == track.size()) {
res.add(new LinkedList<>(track));
return;
}
for (int i = start; i <= n; i++) {
track.addLast(i);
backtrack(n, k, i + 1, track);
track.removeLast();
}
}
}
46. 全排列
class Solution {
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> permute(int[] nums) {
LinkedList<Integer> track = new LinkedList<>();
backtrack(nums,track);
return res;
}
void backtrack(int[] nums, LinkedList track){
if(track.size() == nums.length){
res.add(new LinkedList(track));
return;
}
for(int i = 0; i< nums.length;i++){
if(track.contains(nums[i])){
continue;
}
track.add(nums[i]);
backtrack(nums,track);
track.removeLast();
}
}
}