找子集
List<Integer> temp = new ArrayList<>(); //子集
List<List<Integer>> arr = new ArrayList<>(); //存放子集
public void dfs(Integer[] num, int n){
//讲子集temp添加进arr中
arr.add(new ArrayList<>(temp));
for(int i = n;i< num.length;i++){
temp.add(num[i]);
dfs(num,i+1);
temp.remove(temp.size()-1);
}
}
public List<List<Integer>> tar(Integer [] num){
dfs(num,0);
return arr;
}
Integer num[] = {1,2,3};
System.out.println(Arrays.toString(tar(num).toArray()));
[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
最短路
int row=10,column=11;
int px=6,py=4,min = 2147483646;
int book[][] = new int[row][column];
public final int[][] next={{1,0},{0,1},{0,-1},{-1,0}};
private int map[][] = new int[][]{
{0,0,0,0,0,0,1,1,0,0,0},
{1,0,0,0,0,0,0,0,1,0,1},
{0,0,0,0,1,1,0,0,1,0,1},
{1,0,0,0,1,0,1,0,1,0,0},
{0,0,0,1,0,0,1,0,0,0,0},
{0,1,1,1,0,0,0,0,1,0,1},
{0,0,0,1,0,0,1,0,1,0,1},
{1,0,1,0,1,1,0,0,1,1,1},
{1,1,0,0,0,0,0,0,0,0,0},
{1,0,0,1,1,1,0,0,0,0,1}
};
public void dfs(int x,int y,int n){
int mx,my;
if (x == px && y == py){
if (n < min){
System.out.println("yes\t"+n);
for (int i =0; i<row;i++){
for (int j=0;j<column;j++){
System.out.print(book[i][j]+" ");
}
System.out.println();
}
min = n;
}
return;
}
for(int i = 0;i<4;i++){
mx = x + next[i][0];
my = y + next[i][1];
if ((mx<0 || mx >=row || my<0 || my >=column) || map[mx][my]==1){
continue;
}
if (book[mx][my]==0){
book[mx][my] = 1;
dfs(mx,my,n+1);
book[mx][my] = 0;
}
}
return;
}
二叉树最大深度
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
int max =-1;
int flag = 1;
public int maxDepth(TreeNode root) {
dfs(root,0);
return max;
}
public void dfs(TreeNode root,int n){
if (root == null){
max = 0;
return;
}else if (flag ==1){
n++;
flag=0;
}
if (root.right == null && root.left ==null){
if (n>max){
max = n;
//System.out.println("yes\t" + max);
}
return;
}
if (root.left != null) {
dfs(root.left, n+1);
}
if (root.right != null){
dfs(root.right, n+1);
}
return;
}