• 写法1

class Solution {
Boolean[] visited;
List<String> wordDict;
String s;
public boolean wordBreak(String s, List<String> wordDict) {
visited = new Boolean[s.length()];
this.wordDict = wordDict;
this.s = s;
return dfs(0);
}


public boolean dfs(int i){
if(i == s.length()){
return true;
}
if(visited[i] != null){
return visited[i];
}
for(int j = i + 1; j < s.length(); j++){
String tmp = s.substring(i, j);
if(wordDict.contains(tmp) && dfs(j)){
visited[i] = true;
return true;
}
}
visited[i] = false;
return false;
}
}



  • 写法2

class Solution {
List<List<Integer>> adj;
int[] flags;
public boolean canFinish(int numCourses, int[][] prerequisites) {
flags = new int[numCourses];
adj = new ArrayList<>();
for(int i = 0; i < numCourses; i++){
adj.add(new ArrayList<>());
}
for(int[] p : prerequisites){
adj.get(p[0]).add(p[1]);
}
for(int i = 0; i < numCourses; i++){
if(!dfs(i)){
return false;
}
}
return true;
}
public boolean dfs(int i){
if(flags[i] == 1) return false;
else if(flags[i] == -1) return true;
flags[i] = 1;
for(int j : adj.get(i)){
if(!dfs(j)) return false;
}
flags[i] = -1;
return true;
}
}


class Solution {
List<List<Integer>> adj;
int[] flags;
public boolean canFinish(int numCourses, int[][] prerequisites) {
flags = new int[numCourses];
adj = new ArrayList<>();
for(int i = 0; i < numCourses; i++){
adj.add(new ArrayList<>());
}
for(int[] p : prerequisites){
adj.get(p[0]).add(p[1]);
}
for(int i = 0; i < numCourses; i++){
if(!dfs(i)){
return false;
}
}
return true;
}


// flags[i] == 1 本次dfs访问过, 说明有环, 返回false
// flags[i] == -1 本次dfs外访问过,返回true
// flags[i] == 0 , 未遍历过该节点, 因此需要dfs该节点的邻接节点
public boolean dfs(int i){
if(flags[i] == 1) return false;
else if(flags[i] == -1) return true;
flags[i] = 1;
for(int j : adj.get(i)){
if(!dfs(j)) return false;
}
flags[i] = -1;
return true;
}
}


class Solution {
public int islandPerimeter(int[][] grid) {
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == 1){
return dfs(grid, i, j);
}
}
}
return 0;
}


public int dfs(int[][] grid, int i, int j){
if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length){
return 1;
}
if(grid[i][j] == 0){
return 1;
}
if(grid[i][j] == 2){
return 0;
}
grid[i][j] = 2;
return dfs(grid, i-1, j) +
dfs(grid, i+1, j) +
dfs(grid, i, j-1) +
dfs(grid, i, j+1);
}
}


class Solution {
Set<String> res;
boolean[] visited;
char[] chars;
public String[] permutation(String s) {
visited = new boolean[s.length()];
chars = s.toCharArray();
res = new HashSet<>();
dfs("");
return res.toArray(new String[res.size()]);
}
public void dfs(String tmp){
if(tmp.length() == visited.length){
res.add(tmp);
return;
}
for(int i = 0; i < chars.length; i++){
if(visited[i] == false){
visited[i] = true;
dfs(tmp + chars[i]);
visited[i] = false;
}
}
}
}