Duplicate Calculation in Recursion14

17 篇文章 0 订阅
5 篇文章 0 订阅

Duplicate Calculation in Recursion

Memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again. (Source: wikipedia)
我的理解:递归太耗内存,所以创建一个缓存,减轻内存压力

Fibonacci Number

public int fib(int n) {
        HashMap hashMap=new HashMap<Integer,Integer>();
        if(hashMap.containsKey(n)) return (int) hashMap.get(n);
        if (n==0) return 0;
        if (n==1) return 1;
        int value=fib(n-1)+fib(n-2);
        hashMap.put(n,value);
        return value;
    }

第一种缓存方式:HashMap缓存

Climbing Stairs

You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

public static int climbStairs(int n) {
    if(n == 1)
        return 1;
    int[] res=new int[n];
    res[1]=2;res[0]=1;
    for(int i = 2; i < n; ++i)
      res[i] = res[i-1] + res[i-2];
    return res[n-1];
}

第二种缓存方式:用数组缓存

Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth.

递归迭代
public int maxDepth(TreeNode root) {
        return helper(root,0);
    }
    public int helper(TreeNode root,int counter){
        if(root==null) return counter;
        int l=root.left==null?0:helper(root.left,counter++);
        int r=root.right==null?0:helper(root.right,counter++);
        return 1+Math.max(l,r);
    }
    //更简单的写法
    public int maxDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
    }
   

栈或队列

public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        int depth=0;
        Queue queue = new LinkedList<TreeNode>();
        queue.offer(root);
        if(!queue.isEmpty()){
            int size=queue.size();
            depth++;
            while (size-->0){
                TreeNode tem= (TreeNode) queue.poll();
                if(tem.left!=null) queue.offer(tem.left);
                if(tem.right!=null) queue.offer(tem.right);

            }
        }
        return depth;
    }
    public int maxDepth1(TreeNode root) {
            TreeNode node = root;
            Stack<TreeNode> nodeStack = new Stack<TreeNode>();
            Stack<Integer> depthStack = new Stack<Integer>();

            int max = 0;
            int depth = 1;
            while (node != null || nodeStack.size() > 0)
            {
                if (node != null)
                {
                    nodeStack.push(node);
                    depthStack.push(depth);
                    node = node.left;
                    depth++;
                }
                else
                {
                    node = nodeStack.pop();
                    depth = depthStack.pop();

                    if (depth > max) max = depth;

                    node = node.right;
                    depth++;
                }
            }
            return max;
    }

Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
如果照常规方法,耗时太长

public double pow(double x, int n) {
        if(n == 0)
            return 1;
        if(n<0){
            n = -n;
            x = 1/x;
            //return 1/x * myPow(1/x, -(n + 1));
        }
        return (n%2 == 0) ? pow(x*x, n/2) : x*pow(x*x, n/2);
        //包含递归
    }

Merge Two Sorted Lists

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head =new ListNode(0);
        ListNode res=head;
        while (l1!=null&&l2!=null) {
            if (l1.val <= l2.val) {
                res.next = l1;
                res=res.next;
                l1 = l1.next;
            }else{
                res.next = l2;
                res=res.next;
                l2 = l2.next;
            }
        }
        if(l1==null&&l2!=null)
            res.next=l2;
        if(l1!=null&&l2==null)
            res.next=l1;
        return head.next;
    }
//没有使用 recursion
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
		if(l1 == null) return l2;
		if(l2 == null) return l1;
		if(l1.val < l2.val){
			l1.next = mergeTwoLists(l1.next, l2);
			return l1;
		} else{
			l2.next = mergeTwoLists(l1, l2.next);
			return l2;
		}
}

K-th Symbol in Grammar

We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.

public static int kthGrammar(int n, int k) {
        Queue<List> queue=new LinkedList<>();
        List<Integer> list = new ArrayList<Integer>();
        list.add(0);
        queue.add(list);
        int i=1;
        if (n==1)  i=0;
        while (--n > 1){
            i=i*2;
        }
        while (i-- >0 && !queue.isEmpty()){
            List currlist = queue.poll();
            Integer f = (Integer)currlist.get(0);
            if(f==0) {
                ArrayList<Object> temp = new ArrayList<>();
                temp.add(0);
                temp.add(1);
                queue.add(temp);
            }
            if(f==1) {
                ArrayList<Object> temp = new ArrayList<>();
                temp.add(1);
                temp.add(0);
                queue.add(temp);
            }
            if(currlist.size()>1) {
                Integer s = (Integer) currlist.get(1);
                if (s == 0) {
                    ArrayList<Object> temp = new ArrayList<>();
                    temp.add(0);
                    temp.add(1);
                    queue.add(temp);
                }
                if (s == 1) {
                    ArrayList<Object> temp = new ArrayList<>();
                    temp.add(1);
                    temp.add(0);
                    queue.add(temp);
                }
            }
        }
        List<Integer> reslist = new ArrayList<>();
        if (k==1) return 0;
        while (k>0){
            reslist = queue.poll();
            k=k-2;
        }
        k=k+2;
        if (k==1) return reslist.get(0);
        else return reslist.get(1);
    }

非常惭愧,15/55就已经time limit exceeded
但思路应该是没有问题的,也没有用到递归

class Solution {
    public int kthGrammar(int N, int K) {
        if(N==1) return 0;
        if(K%2==0){
            if (kthGrammar(N-1,K/2)==0) return 1;
            else return 0;
        }
        else{
            if(kthGrammar(N-1,(K+1)/2)==0) return 0;
            else return 1;
        }
    }
}
 public int kthGrammar(int n, int k) {
        if(n==1 && k==1)
            return 0;
        
        int mid = (int)Math.pow(2,n-1) / 2;
        
        if(k<=mid)         
            return kthGrammar(n-1,k);
        else
            return (kthGrammar(n-1,k-mid) == 0? 1:0);
       
    }

Unique Binary Search Trees II

Given an integer n, return all the structurally unique BST’s (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order

public List<TreeNode> generateTrees(int n) {
        return helper(1,n);
    }
    public List<TreeNode> helper(int start,int end){
        ArrayList<TreeNode> res = new ArrayList<>();
        if (start>end){
            res.add(null);
            return res;
        }
        for (int i=start;i<=end;i++){
            List<TreeNode> left = helper(start, i);
            List<TreeNode> right = helper(i + 1, end);
            for (TreeNode r:right){
                for (TreeNode l:left){
                    TreeNode node = new TreeNode(i);
                    node.left=l;
                    node.right=r;
                    res.add(node);
                }
            }

        }
        return res;
    }

懵懵懂懂,找机会再写一遍

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值