LC剑指 Offer 38. 字符串的排列
//经典的排列组合题型,有很多细节的地方没有处理好,比方说需要对数组进行排序以及设置标记。同时结束的递归函数的递归出口也出了差错
class Solution {
private List<String> res;
private boolean[] flag;//mark
public String[] permutation(String s) {
int n = s.length();
res = new ArrayList();
char[] ch = s.toCharArray();
StringBuffer sb = new StringBuffer();
flag = new boolean[n];
//mark
Arrays.sort(ch);
dfs(n,ch,sb,0);
String[] ans = new String[res.size()];
for(int i = 0;i < ans.length;i++){
ans[i] = res.get(i);
}
return ans;
}
public void dfs(int n,char[] ch,StringBuffer sb,int i){
//mark
if(i == n){
res.add(sb.toString());
return;
}
for(int j = 0;j < n;j++){
if(flag[j] || (j > 0 && !flag[j- 1] && ch[j] == ch[j - 1])){
continue;
}
flag[j] = true;
sb.append(ch[j]);
dfs(n,ch,sb,i + 1);
sb.deleteCharAt(sb.length() - 1);
flag[j] = false;
}
}
}
LC701. 二叉搜索树中的插入操作
//递归模板,需要查看当前插入的值是否大于或小于根节点的值,只需要不断递归查找到当前位置为空的话,也就是说已经找到了位置,放入即可。
/**
* 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 {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null){
return new TreeNode(val);
}
if(val < root.val){
root.left = insertIntoBST(root.left,val);
}else{
root.right = insertIntoBST(root.right,val);
}
return root;
}
}
LC530. 二叉搜索树的最小绝对差
//二叉搜索树,第一反应就要想到中序遍历,并且最小值的绝对差肯定是相邻两个元素之间。使用一个pre保存上一个节点的值,并且定义一个全局变量ans遍历到最后就返回最终结果即可。
/**
* 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 {
private int ans;
private int pre;
public int getMinimumDifference(TreeNode root) {
ans = Integer.MAX_VALUE;
pre = -1;
dfs(root);
return ans;
}
public void dfs(TreeNode root){
if(root == null){
return;
}
dfs(root.left);
if(pre == -1){
pre = root.val;
}else{
ans = Math.min(ans,root.val - pre);
pre = root.val;
}
dfs(root.right);
}
}