放牌
三个盒子放三张牌1,2,3、找出所有不同的放法
public static void dfs(int index, int n, int[] box, int[] card) {
if (index == n + 1) {
for (int i = 1; i < box.length; i++) {
System.out.print(box[i] + " ");
}
System.out.println();
// return;
}
for (int i = 1; i <= n; i++) {
if (card[i] == 0) {
box[index] = i;//如果当前的牌还没有被用的话、那么九江box的index 的位置放入这张牌
card[i] = 1;//然后将这张牌置为1,表示这张牌已经被用了
//然后来看箱子的下一个位置
dfs(index + 1, n, box, card);
//最后回溯、拿走这张牌、尝试其它的牌
card[i] = 0;
}
}
}
690.员工的重要性
class Solution690 {
private int dfs(List<Employee> employees, int id) {
Employee cur = null;
for (int i = 0; i < employees.size(); i++) {
if (employees.get(i).id == id) {
cur = employees.get(i);
}
}
int res = cur.importance;
for (Integer childId : cur.subordinates) {
res += dfs(employees, childId);
}
return res;
}
public int getImportance(List<Employee> employees, int id) {
return dfs(employees, id);
}
}
class Solution690_1 {
public int dfs(HashMap<Integer, Employee> hashMap, int id) {
Employee employee = hashMap.get(id);
int res = employee.importance;
for (int curId : employee.subordinates) {
res += dfs(hashMap, curId);
}
return res;
}
public int getImportance(List<Employee> employees, int id) {
HashMap<Integer, Employee> hashMap = new HashMap<>();
for (int i = 0; i < employees.size(); i++) {
hashMap.put(employees.get(i).id, employees.get(i));
}
return dfs(hashMap, id);
}
}
733.图像渲染
class Solution733 {
int[][] pNext = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public void dfs(int[][] image, int row, int col, int newX, int newY, int oldColor, int newColor, int[][] used) {
image[newX][newY] = newColor;
used[newX][newY] = 1;
for (int i = 0; i < 4; i++) {
int nextX = newX + pNext[i][0];
int nextY = newY + pNext[i][1];
if (nextX < 0 || nextX >= row || nextY < 0 || nextY >= col)
continue;
if (image[nextX][nextY] == oldColor && used[nextX][nextY] == 0) {
dfs(image, row, col, nextX, nextY, oldColor, newColor, used);
}
}
}
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int row = image.length;
int col = image[0].length;
int[][] used = new int[row][col];
dfs(image, row, col, sr, sc, image[sr][sc], newColor, used);
return image;
}
}