算法
merge-two-sorted-lists
解决办法: 递归
public class Solution{
public ListNode mergeTwoLists(ListNode l1,ListNode l2){
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
ListNode mergeHead;
if(l1.val<l2.val){
mergeHead=l1;
mergeHead.next=mergeTwoLists(l1.next,l2);
}else{
mergeHead=l2;
mergeHead.next=mergeTwoLists(l1,l2.next);
}
return mergeHead;
}
}
解决方法:backtracking solution(回溯法)
此例运用递归回溯的方式
public List<String> generateParenthesis(int n){
List<String> list =new ArrayList<String> ();
backtrack(list,"",0,0,n);
return list;
}
public void backtrack(List<String> list,String str,int open,int close,int max){
if(str.length()==max*2){
list.add(str);
}
if(open<max)
backtrack(list,str+"(",open+1,close,max);
if(close<open)
backtrack(list,str+")",open,close+1,max);
}
网友评论