Problem 22. 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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
解题思路:
1. 首先考虑符合要求的字符串格式,(1)任何时刻,左括号的数量都要大于等于右括号的数量,(2)同时对于每一个右括号,前面都必须有一个左括号与之对应;
2. 所以我们可以考虑通过递归来一个一个括号的进行添加,将最后符合要求的结果保存起来即可。
3. 从空字符串开始,首先先添加一个左括号,如果左括号的数量小于要求的数量,则继续递归添加左括号,同时,如果右括号的数量小于左括号的数量,也继续递归添加右括号,这样先添加左括号,再添加右括号的流程,保证了条件(1)和条件(2)都能够被满足,所以这种方式生成的字符串,都是符合要求的结果。
代码如下:
public class Solution {
private List<String> resList;
public List<String> generateParenthesis(int n) {
resList = new ArrayList<>();
add("",0,0,n);
return resList;
}
public void add(String str,int start,int stop,int max){
if(str.length() == max *2 && start == stop){
resList.add(str);
return;
}
if(str.length()>=max*2 || start > max || stop > max){
return;
}
if(start < max){
add(str+'(',start+1,stop,max);
}
if(stop < start){
add(str+')',start,stop+1,max);
}
}
}
Problem 24. 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.
解题思路:
1. 首先题目要求不能改变ListNode的值,所以我们不能直接简单粗暴的进行值交换,需要考虑链表的结构来进行节点交换;
2. 核心过程就是两个节点的交换,接收三个ListNode,包括需要交换的两个ListNode node1和node2,还有node1前面的ListNode pre;
3. 第一步首先用一个temp node 记录node2 的next,然后第二步把node2 的next指向node1 ,第三步把node1的next指向第一步记录的node2的next,最后一步把pre的next指向node2,这样就完成了node1和node2的交换。思路如下图所示:
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode pre = new ListNode(0);
pre.next = head;
ListNode node1,node2,Head;
Head = pre;
while(pre.next != null && pre.next.next != null){
node1 = pre.next;
node2 = node1.next;
swap(pre,node1,node2);
pre = pre.next.next;
}
return Head.next;
}
public void swap(ListNode pre,ListNode node1,ListNode node2){
ListNode temp = new ListNode(0);
temp.next = node2.next;
node2.next = node1;
node1.next = temp.next;
pre.next = node2;
}
}