第二十八天——搜索与回溯算法
第一题:剑指 Offer 37. 序列化二叉树
问题描述
思路
代码(手动狗头)
别问为什么,直接保命要紧
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
TreeNode root;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
this.root = root;
return null;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
时间空间复杂度
递归实现
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null) return "null,";
String str = root.val + ",";
str += serialize(root.left);
str += serialize(root.right);
return str;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String array[] = data.split(",");
Queue<String> queue = new LinkedList<>();
for(int i=0;i<array.length;i++){
queue.offer(array[i]);
}
return help(queue);
}
public TreeNode help(Queue<String> queue){
String val = queue.poll();
if(val.equals("null")) return null;
TreeNode root = new TreeNode(Integer.valueOf(val));
root.left = help(queue);
root.right = help(queue);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
时间空间复杂度
第二题:剑指 Offer 38. 字符串的排列
问题描述
思路
代码
class Solution {
public String[] permutation(String s) {
Set<String> list = new HashSet<>();
char[] array = s.toCharArray();
StringBuilder str = new StringBuilder();
boolean[] visited = new boolean[array.length];
dfs(array,"",visited,list);
return list.toArray(new String[0]);
}
public void dfs(char[] array,String s,boolean[] visited,Set<String>list){
if(s.length() == array.length){
list.add(s);
return;
}
for(int i=0;i<array.length;i++){
if(visited[i]) continue;
visited[i] = true;
dfs(array,s+String.valueOf(array[i]),visited,list);
visited[i] = false;
}
}
}