LeetCode104.Maximum Depth of Binary Tree 计算最大深度。
比较经典的递归做法。
//找到二叉树的最大深度
//离根节点最远的叶子节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
else{//m为左侧的深度,n为右侧的深度
//递归,深搜
int m=maxDepth(root.left);
int n=maxDepth(root.right);
if(m>n) return m+1;
else return n+1;
}
}
}
LeetCode494 TargetSum 使用dfs算法来做,比较简单直接。
//深度搜索从数组开始进行求和。
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols
+
and
-
. For each integer, you should choose one from
+
and
-
as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 There are 5 ways to assign symbols to make the sum of nums be target 3.
class Solution {
public int findTargetSumWays(int[] nums, int S) {
return dfs(nums,0,S);
}
public int dfs(int[] nums,int i,int sum){
if(i==nums.length){
if(sum==0) return 1;//成功
else return 0;//失败
}
int ways=0;
ways+=dfs(nums,i+1,sum-nums[i]); //-号遍历
ways+=dfs(nums,i+1,sum+nums[i]); //+号遍历
return ways;//返回结果
}
}
LeetCode547 FriendCircle(朋友圈)
//计算朋友圈的数量
//题目中的意思是第一个朋友圈中有((0,0),(0,1),(1,0),(1,1)),第二个朋友圈是(2,2)
//深度优先遍历能遍历所有值为1的结点,通过图的连通性来实现。
//visit记录连通性的好坏。
public class Solution {
public int findCircleNum(int[][] M) {
int[] visited = new int[M.length];
int count = 0;
for (int i = 0; i < M.length; i++) {
if (visited[i] == 0) {
dfs(M, visited, i);
count++;
}
}
return count;
}
public void dfs(int[][] M, int[] visited, int i) {
for (int j = 0; j < M.length; j++) {
if (M[i][j] == 1 && visited[j] == 0) {
visited[j] = 1;
dfs(M, visited, j);
}
}
}
}
LeetCode37 Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'
.
You may assume that there will be only one unique solution.
A sudoku puzzle...
...and its solution numbers marked in red.
//数独游戏本身的玩法是每一个行每一列都为1-9不重复
//循环处理子问题,对于每个格子,带入不同的9个数
//然后判断合法性,如果成立就递归继续,结束后把数字设为“.”
class Solution {
public void solveSudoku(char[][] board) {
if(board==null||board.length==0) return;
dfs(board);
}
private boolean dfs(char[][] board){
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]=='.'){
for(char c='1';c<='9';c++){
if(isValid(board,i,j,c)){
board[i][j]=c;
if(dfs(board)) return true;
else board[i][j]='.';
}
}
/*运行到此说明这个位置不能确定具体的数字*/
return false;
}
}
}
return true;
}
//判断是否是一个正确的数独(36)
private boolean isValid(char[][] board,int row,int col,char c){
for(int i=0;i<board.length;i++){
//判断col列和row行是否满足数独条件
if(board[i][col]==c||board[row][i]==c) return false;
//判断九宫格
if(board[3*(row/3)+i/3][3*(col/3)+i%3]==c)
return false;
}
return true;
}
}
leetcode37题参考为:http://blog.youkuaiyun.com/mine_song/article/details/70195463
题解思路有参考。