首页 > 代码库 > Leetcode 记录

Leetcode 记录

 

21.Merge Two Sorted List

需要创建一个头结点

技术分享
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
12         ListNode dummy(0);
13         ListNode *ans = &dummy;
14         while(l1!=NULL&&l2!=NULL){
15             if(l1->val<l2->val){
16                 ans->next=l1;
17                 l1=l1->next;
18             }
19             else{
20                 ans->next=l2;
21                 l2=l2->next;
22             }
23             ans=ans->next;
24         }
25         ans->next = l1 ? l1 : l2;
26         return dummy.next;
27     }
28 };
View Code

 22.Generate Parentheses

递归

技术分享
 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> ans;
 5         vector<string> ans1;
 6         vector<string> ans2;
 7         for(int i=1;i<2*n;i+=2){
 8             ans1=generateParenthesis((i-1)/2);
 9             ans2=generateParenthesis((2*n-i-1)/2);
10             ans1.push_back("");
11             ans2.push_back("");
12             for(int j=0;j<ans1.size();j++){
13                 for(int k=0;k<ans2.size();k++){
14                     string m=(+ans1[j]+)+ans2[k];
15                     if(m.length()!=2*n)  continue;
16                     ans.push_back(m);
17                 }
18             }
19         }
20         return ans;
21     }
22 };
View Code

 

Leetcode 记录