Generate Parentheses
问题描述
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
分析
使用递归的策略求解,使用n记录“(”的个数,m记录“)”的个数,当m和n都为0时,代表生成了一种可能。
解答
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
add(result, "", n, 0);
return res;
}
void add(vector<string> &res, string str, int n, int m)
{
if(n==0 && m==0)
res.push_back(str);
if(m > 0)
add(res, str+")", n, m-1);
if(n > 0)
addr(res, str+"(", n-1, m+1);
}
};
Swap Nodes in Pairs
问题描述
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
分析
依次判别链表两个元素不为空时交换它们的位置即可。
解答
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode result(0);
result.next = head;
ListNode *p = &result;
for ( ; head != NULL && head->next != NULL; p = head, head = p->next)
{
p->next = head->next;
p = p->next;
head->next = p->next;
p->next = head;
}
return result.next;
}
};