目录
4.4分解让复杂问题简单化
剑指 Offer 35. 复杂链表的复制
题目
代码
法一:哈希表+递归
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
//建立节点与新节点之间的映射
unordered_map<Node*, Node* >cachenode;
Node* copyRandomList(Node* head) {
if(head == nullptr) {
return nullptr;
}
if(!cachenode.count(head)) {
Node* newhead = new Node(head->val);
cachenode[head] = newhead;
newhead->next = copyRandomList(head->next);
newhead->random = copyRandomList(head->random);
}
return cachenode[head];
}
};
法二:哈希表+迭代
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
//哈希表,迭代
Node* copyRandomList(Node* head) {
if(head == nullptr) {
return nullptr;
}
Node* cur = head;
unordered_map<Node*,Node*>cachenode;
//建立节点映射
while(cur != nullptr) {
Node* newhead = new Node(cur->val);
cachenode[cur] = newhead;
cur = cur->next;
}
cur = head;
//连接next和random
while(cur != nullptr) {
cachenode[cur]->next = cachenode[cur->next];
cachenode[cur]->random = cachenode[cur->random];
cur = cur->next;
}
//返回新链表的头节点
return cachenode[head];
}
};
法三:拼接+拆分
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == nullptr) {
return nullptr;
}
//拆分加拼接
//拼接,新节点插入旧节点之后
Node* cur = head;
while(cur != nullptr) {
Node* temp = new Node(cur->val);
temp->next = cur->next;
cur->next = temp;
cur = temp->next;
}
//random
cur = head;
while(cur != nullptr) {
if(cur->random != nullptr) {
cur->next->random = cur->random->next;
}
cur = cur->next->next;
}
//拆分
cur = head->next;
Node* pre = head, *res = head->next;
//pre和cur分别操作拆开的链表
while(cur->next != nullptr) {
pre->next = pre->next->next;
cur->next = cur->next->next;
pre = pre->next;
cur = cur->next;
}
pre->next = nullptr; // 单独处理原链表尾节点
return res; // 返回新链表头节点
}
};
剑指 Offer 36. 二叉搜索树与双向链表
题目
代码
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node() {}
Node(int _val) {
val = _val;
left = NULL;
right = NULL;
}
Node(int _val, Node* _left, Node* _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
public:
Node* head,*pre;
//二叉搜索树中序遍历
void dfs(Node* cur) {
if(cur == nullptr) {
return;
}
dfs(cur->left);
//当 pre 为空时: 代表正在访问链表头节点,记为 head
if(pre == nullptr) {
head = cur;
}
//当 pre 不为空时:修改双向节点引用
else pre->right = cur;
cur->left = pre;
pre = cur;
dfs(cur->right);
}
Node* treeToDoublyList(Node* root) {
if(root == nullptr) {
return nullptr;
}
//构建循环链表
dfs(root);
head->left = pre;
pre->right = head;
return head;
}
};
剑指 Offer 37. 序列化二叉树
题目
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
// 层序遍历
string res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* front = q.front();
q.pop();
if (front) {
res += to_string(front->val) + ",";
q.push(front->left);
q.push(front->right);
}
else res += "null,";
}
//去除最后一个逗号
return res.substr(0, res.size() - 1);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data.empty()) return nullptr;
vector<string> s = split(data);
queue<TreeNode*> q;
TreeNode* root = new TreeNode(stoi(s[0]));
q.push(root);
int i = 1;
while (!q.empty()) {
TreeNode* front = q.front();
q.pop();
if (s[i] != "null") {
front->left = new TreeNode(stoi(s[i]));
q.push(front->left);
}
++i;
if (s[i] != "null") {
front->right = new TreeNode(stoi(s[i]));
q.push(front->right);
}
++i;
}
return root;
}
vector<string> split(string& s) {
vector<string> res;
int n = s.size();
int i = 0;
//s[i]到s[j]表示了一个节点的值,将其分隔开存入向量中
while (i < n) {
int j = i + 1;
while (j < n && s[j] != ',') ++j;
res.push_back(s.substr(i, j - i));
i = j + 1;
}
return res;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
剑指 Offer 38. 字符串的排列
题目
代码
方法一:排序加回溯
class Solution {
public:
vector<string>res;
vector<int>vis;
void backtrack(string s,int x, int n,string& str) {
if(x == n ) {
res.push_back(str);
return;
}
for(int j = 0; j < n; j++) {
//保证在填每一个空位的时候重复字符只会被填入一次
//排序之后相同的元素会相邻
//vis[j-1]==false表示s[j-1]的所有可能已经遍历完成
if(vis[j] || (j > 0 && !vis[j - 1] && s[j - 1] == s[j])) {
continue;
}
vis[j] = true;
str.push_back(s[j]);
backtrack(s,x+1,n,str);
vis[j] = false;
str.pop_back();
}
}
vector<string> permutation(string s) {
int n = s.size();
//这一步不能少
vis.resize(n);
sort(s.begin(),s.end());
string str;
backtrack(s,0,n,str);
return res;
}
};
方法二:交换+回溯
class Solution {
public:
vector<string>res;
void dfs(string s,int x) {
if(x == s.size() - 1) {
res.push_back(s);
}
set<char>st;
for(int i = x; i < s.size();i++) {
//去除重复
if(st.find(s[i]) != st.end()) {
continue;
}
st.insert(s[i]);
//交换
swap(s[i],s[x]);
dfs(s,x+1);
//撤销交换
swap(s[i],s[x]);
}
}
vector<string> permutation(string s) {
dfs(s,0);
return res;
}
};
扩展:n皇后问题
class Solution {
public:
vector<vector<string>>res;
/* 是否可以在 board[row][col] 放置皇后? */
bool isValid(vector<string>& board, int row, int col) {
int n = board.size();
// 检查列是否有皇后互相冲突
for (int i = 0; i < n; i++) {
if (board[i][col] == 'Q')
return false;
}
// 检查右上⽅是否有皇后互相冲突
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (board[i][j] == 'Q')
return false;
}
// 检查左上⽅是否有皇后互相冲突
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q')
return false;
}
return true;
}
// 路径:board 中⼩于 row 的那些⾏都已经成功放置了皇后
// 选择列表:第 row ⾏的所有列都是放置皇后的选择
void backtrack(int row,vector<string>& board) {
if(row == board.size() ) {
res.push_back(board);
return;
}
int n = board.size();
//排列
for(int col = 0; col < n; col++) {
//排除不符合条件的
if(!isValid(board,row,col)) {
continue;
}
//做选择
board[row][col] = 'Q';
backtrack(row + 1, board);
//撤销选择
board[row][col] = '.';
}
}
//全排列问题
vector<vector<string>> solveNQueens(int n) {
//初始化空棋盘
vector<string> board(n,string(n,'.'));
backtrack(0,board);
return res;
}
};