1、合并排序链表
给定一个链表数组,每个链表都已经按升序排列。
请将所有链表合并到一个升序链表中,返回合并后的链表。
思路:无脑遍历所有的元素,用vector存储后sort排序,创建新链表返回即可
/**
* 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* mergeKLists(vector<ListNode*>& lists) {
ListNode*pre=NULL;
ListNode*p=NULL;
ListNode*head=NULL;
int n=lists.size();
vector<int>nums;
for(int i=0;i<n;i++){
while(lists[i]!=NULL){
nums.emplace_back(lists[i]->val);
lists[i]=lists[i]->next;
}
}
sort(nums.begin(),nums.end());
int m=nums.size();
for(int i=0;i<m;i++){
p=new ListNode(nums[i]);
if(pre!=NULL){
pre->next=p;
}else{
head=p;
}
pre=p;
}
return head;
}
};
2、所有子集
给定一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
思路:其实本质上依然是一个dfs的深搜的问题,套用基本模板即可
class Solution {
public:
vector<vector<int> >ans;
vector<int>array;
int n;
void dfs(int i,vector<int>&temp){
temp.emplace_back(array[i]);
ans.emplace_back(temp);
for(int j=i+1;j<n;j++){
dfs(j,temp);
}
temp.pop_back();
}
vector<vector<int>> subsets(vector<int>& nums) {
//返回所有子集2的n方
vector<int>temp;
ans.emplace_back(temp);
n=nums.size();
array=nums;
for(int i=0;i<n;i++){
dfs(i,temp);
}
return ans;
}
};