2024/9/9 Hot100 回溯
This commit is contained in:
parent
4d20f5dee9
commit
c8f22deef1
|
@ -0,0 +1,49 @@
|
|||
package com.cool.hot100.backtracking;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created with IntelliJ IDEA.
|
||||
*
|
||||
* @Author: Cool
|
||||
* @Date: 2024/09/09/14:39
|
||||
* DayNumber 2
|
||||
* Hard 2
|
||||
* Level ?
|
||||
*/
|
||||
public class Num46 {
|
||||
|
||||
|
||||
List<List<Integer>> resList = new ArrayList<>();
|
||||
List<Integer> list = new ArrayList<>();
|
||||
|
||||
public List<List<Integer>> permute(int[] nums) {
|
||||
for (int num : nums) {
|
||||
list.add(num);
|
||||
}
|
||||
dfs(0);
|
||||
return resList;
|
||||
}
|
||||
|
||||
private void dfs(int x) {
|
||||
if (x == list.size() - 1) {
|
||||
resList.add(new ArrayList<>(list));
|
||||
return;
|
||||
}
|
||||
for (int i = x; i < list.size(); i++) {
|
||||
swap(i, x);
|
||||
dfs(x + 1);
|
||||
swap(i, x);
|
||||
}
|
||||
}
|
||||
|
||||
private void swap(int x, int y) {
|
||||
int temp = list.get(x);
|
||||
list.set(x, list.get(y));
|
||||
list.set(y, temp);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.cool.hot100.backtracking;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created with IntelliJ IDEA.
|
||||
*
|
||||
* @Author: Cool
|
||||
* @Date: 2024/09/09/16:57
|
||||
* DayNumber 3
|
||||
* Hard 2
|
||||
* Level ?
|
||||
*/
|
||||
public class Num78 {
|
||||
|
||||
List<List<Integer>> resList = new ArrayList<>();
|
||||
List<Integer> list = new ArrayList<>();
|
||||
|
||||
public List<List<Integer>> subsets(int[] nums) {
|
||||
dfs(nums, 0);
|
||||
return resList;
|
||||
}
|
||||
|
||||
private void dfs(int[] nums, int index) {
|
||||
resList.add(new ArrayList<>(list));
|
||||
if (index >= nums.length) {
|
||||
return;
|
||||
}
|
||||
for (int i = index; i < nums.length; i++) {
|
||||
list.add(nums[i]);
|
||||
dfs(nums, i+1);
|
||||
list.remove(list.size() - 1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue