汉诺塔
class Solution {
public:
void hanota(vector<int>& A, vector<int>& B, vector<int>& C) {
dfs(A, B, C, A.size());
}
void dfs(vector<int>& x, vector<int>& y, vector<int>& z, int n) {
if (n == 1) {
// z.push_back(x[0]); //error
z.push_back(x.back());
// auto pos = find(x.begin(), x.end(), x[0]); // error
// x.erase(pos);
x.pop_back();
return;
}
dfs(x, z, y, n - 1);
// z.push_back(x[0]);
// auto pos = find(x.begin(), x.end(), x[0]);
// x.erase(pos);
z.push_back(x.back());
x.pop_back();
dfs(y, x, z, n - 1);
return;
}
};
合并有序链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
return dfs(list1, list2);
}
ListNode* dfs(ListNode* list1, ListNode* list2)
{
if(list1 == nullptr) return list2;
if(list2 == nullptr) return list1;
ListNode* res = list1->val < list2->val ? list1 : list2;
if(res == list1)
res->next = dfs(list1->next, list2);
else
res->next = dfs(list2->next, list1);
return res;
}
};