剑指 Offer 13. 机器人的运动范围
class Solution {
//利用used数组来确保dfs过程中方格已经判断过
boolean[][] used;
public int movingCount(int m, int n, int k) {
//此题自己做时,和矩阵中的路径搞混了的一点是没有分析出此题不需要进行回溯撤销操作
used=new boolean[m][n];
return dfs(0,0,m,n,k);
}
public int dfs(int i,int j,int m,int n,int k){
if(i>m-1 || j>n-1 || sum(i,j)>k || used[i][j]==true){
return 0;
}
used[i][j]=true;
return 1+dfs(i,j+1,m,n,k)+dfs(i+1,j,m,n,k);
}
public int sum(int m,int n){
int count=0;
while(m!=0){
int t1=m%10;
count+=t1;
m/=10;
}
while(n!=0){
int t2=n%10;
count+=t2;
n/=10;
}
return count;
}
}
剑指 Offer 34. 二叉树中和为某一值的路径
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<List<Integer>> res=new ArrayList<>();
List<Integer> temp=new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
//错因:回溯撤销操作不会写
dfs(root,target,0);
return res;
}
public void dfs(TreeNode root,int target,int sum){
if(root==null) return;
temp.add(root.val);
sum+=root.val;
if(sum==target&&root.right==null&&root.left==null){
res.add(new ArrayList<>(temp));
}
//注意判断顺序
// temp.add(root.val);
// sum+=root.val;
dfs(root.left,target,sum);
dfs(root.right,target,sum);
//回溯撤销操作
sum-=root.val;
temp.remove(temp.size()-1);
}
}
剑指 Offer 36. 二叉搜索树与双向链表
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val,Node _left,Node _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
Node head;
Node cur;
Node temp;
public Node treeToDoublyList(Node root) {
if(root==null ) return root;
//思路:本文解法基于性质:二叉搜索树的中序遍历为 递增序列 。
//若它的左子树不为空,则左子树上所有结点的值都小于根结点的值。
//若它的右子树不为空,则右子树上所有结点的值都大于根结点的值。
//它的左右子树也分别是二叉搜索树。
//中序遍历构造递增双向链表,再首尾相连实现循环操作
dfs(root);
cur.right=head;
head.left=cur;
return head;
}
public void dfs(Node root){
if(root==null) return;
dfs(root.left);
if(head==null){
head=root;
temp=head;
cur=head;
}
else{
cur=root;
temp.right=cur;
cur.left=temp;
temp=cur;
}
dfs(root.right);
}
}