算法专题十一:递归

汉诺塔问题

面试题 08.06. 汉诺塔问题 - 力扣(LeetCode)

第一步

第二步

将A中的剩下的那个移到C中

第三步

将B中的借助A移到C中

总体的逻辑就是这样,看成三部分

class Solution {
    public void hanota(List<Integer> a, List<Integer> b, List<Integer> c) {
        dfs(a,b,c,a.size());
    }

    public void dfs(List<Integer> a, List<Integer> b, List<Integer> c,int n){
        if(n==1){
            c.add(a.remove(a.size()-1));
            return ;
        }

        dfs(a,c,b,n-1);
        c.add(a.remove(a.size()-1));
        dfs(b,a,c,n-1);

    }
}

合并两个有序列表

21. 合并两个有序链表 - 力扣(LeetCode)

fna

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1==null){
            return list2;
        }
        if(list2==null){
            return list1;
        }
        if(list1.val<=list2.val){
            list1.next=mergeTwoLists(list1.next,list2);
            return list1;            
        }else{
            list2.next=mergeTwoLists(list2.next,list1);
            return list2;
        }

    }
}

反转链表

可以使用递归的方法,也可以使用链表循环的方法,进行顺序的修改

206. 反转链表 - 力扣(LeetCode)

法一:递归进行逆序

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null){
            return head;
        
        }
        ListNode cur=head;
        ListNode newHead=reverseList(cur.next);
        cur.next.next=cur;
        cur.next=null;
        return newHead;
    }


}

法二:链表循环进行逆序

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null ||head.next==null){
            return head;
        }
        ListNode cur=head.next;
        head.next=null;
        ListNode curN=cur.next;
        ListNode prev=head;
        while(cur.next!=null){
            cur.next=prev;
            prev=cur;
            cur=curN;
            curN=curN.next;
        }
        cur.next=prev;
        return cur;
        
    }
}

两两交换链表中的节点

24. 两两交换链表中的节点 - 力扣(LeetCode)

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }

        ListNode newHead=swapPairs(head.next.next);
        ListNode cur=head.next;
        cur.next=head;
        head.next=newHead;
        return cur;
        
    }
}

pow(x,n)

50. Pow(x, n) - 力扣(LeetCode)

class Solution {
    public double myPow(double x, int n) {
        long N=n;
     return N<0?pow(1.0/x,-N):pow(x,N);
    }

    public double pow(double x, long n){
        
        if(n==0){
            return 1.0;
        }
        double tem=pow(x,n/2);
        return n%2==0?tem*tem:tem*tem*x;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值