前言

本文隶属于专栏《LeetCode 刷题汇总》,该专栏为笔者原创,引用请注明来源,不足和错误之处请在评论区帮忙指出,谢谢!

本专栏目录结构请见LeetCode 刷题汇总

正文

幕布

在这里插入图片描述

幕布链接

91. 解码方法

解法

官方解法

动态规划

object Solution {
  def numDecodings(s: String): Int = {
    //开头不能为 0
    if (s(0) == '0') return 0
    val n = s.length
    //dp 表示前 i+1 项对应的解码总数,这里长度取 n+1 是为了方便处理临界场景
    val dp = new Array[Int](n + 1)
    //初始赋值
    dp(0) = 1
    dp(1) = 1
    for (i <- 2 to n) {
      //遍历的当前项对应的数字,s 的索引为 dp 的索引 - 1
      val cur = s(i - 1) - '0'
      //遍历的前一项对应的数字
      val pre = s(i - 2) - '0'
      //不存在下面2种情况:1.连续两项都为 0  2.30
      if (cur + pre == 0 || (cur == 0 && pre > 2)) return 0
      //如果当前项为 0,则必须依赖前一项的数字,解码总数等于 dp(i-2),如果当前项不为 0,前一项为 0,则等于 dp(i-1)
      else if (cur == 0 || pre == 0) dp(i) = if (cur == 0) dp(i - 2) else dp(i - 1)
      //考虑前一项和当前项组成的数字是否大于 26
      else dp(i) = if (pre * 10 + cur > 26) dp(i - 1) else dp(i - 2) + dp(i - 1)
    }
    dp(n)
  }
}

92. 反转链表 II

解法

Simple Java solution with clear explanation

双指针+哨兵

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head == null) return null;
        ListNode dummy = new ListNode(0), pre = dummy;
        dummy.next = head;
        for(int i = 0; i < m - 1 ; i++) pre = pre.next;
        
        ListNode start = pre.next;
        ListNode then = start.next;
        
        // 1 - 2 -3 - 4 - 5 ; m=2; n =4 ---> pre = 1, start = 2, then = 3
        // dummy-> 1 -> 2 -> 3 -> 4 -> 5
        
        for(int i = m; i < n; i++)
        {
            start.next = then.next;
            then.next = pre.next;
            pre.next = then;
            then = start.next;
        }
        
        // first reversing : dummy->1 - 3 - 2 - 4 - 5; pre = 1, start = 2, then = 4
        // second reversing: dummy->1 - 4 - 3 - 2 - 5; pre = 1, start = 2, then = 5 (finish)
        
        return dummy.next;
        
    }
}

93. 复原 IP 地址

DFS,特殊考虑 0

Very simple DFS solution

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<>();
        doRestore(result, "", s, 0);
        return result;
    }
    
    private void doRestore(List<String> result, String path, String s, int k) {
        if (s.isEmpty() || k == 4) {
            if (s.isEmpty() && k == 4)
                result.add(path.substring(1));
            return;
        }
        for (int i = 1; i <= (s.charAt(0) == '0' ? 1 : 3) && i <= s.length(); i++) {
            String part = s.substring(0, i);
            if (Integer.valueOf(part) <= 255)
                doRestore(result, path + "." + part, s.substring(i), k + 1);
        }
    }
}

4层循环,parse and append

WHO CAN BEAT THIS CODE ?

class Solution {
    public List<String> restoreIpAddresses(String s) {
		List<String> ret = new ArrayList<>();
		
		StringBuilder ip = new StringBuilder();
		for(int a = 1 ; a < 4 ; ++a)
		for(int b = 1 ; b < 4 ; ++b)
	    for(int c = 1 ; c < 4 ; ++c)
		for(int d = 1 ; d < 4 ; ++d)
		{
			if(a + b + c + d == s.length() )
			{
				int n1 = Integer.parseInt(s.substring(0, a));
				int n2 = Integer.parseInt(s.substring(a, a+b));
				int n3 = Integer.parseInt(s.substring(a+b, a+b+c));
				int n4 = Integer.parseInt(s.substring(a+b+c));
				if(n1 <= 255 && n2 <= 255 && n3 <= 255 && n4 <= 255)
				{
					ip.append(n1).append('.').append(n2).append('.').append(n3).append('.').append(n4);
					if(ip.length() == s.length() + 3) ret.add(ip.toString());
					ip.setLength(0);
				}
			}
		}
		return ret;
    }
}

94. 二叉树的中序遍历

解法

【专题讲解】 二叉树的前中后序非递归遍历 leetcode 94 144 145

递归

class Solution {
    private List<Integer> res = new ArrayList<>();
    public List<Integer> inorderTraversal(TreeNode root) {
        helper(root);
        return res;
    }

    private void helper(TreeNode node){
        if(node == null) return;
        helper(node.left);
        res.add(node.val);
        helper(node.right);
    }
}

迭代

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Deque<TreeNode> stack = new ArrayDeque<>();
        while(root != null || !stack.isEmpty()){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            list.add(root.val);
            root = root.right;
        }
        return list;
    }
}

95. 不同的二叉搜索树 II

解法

A simple recursive solution

递归

class Solution {
    public List<TreeNode> generateTrees(int n) {
        return genTreeList(1, n);
    }

    private List<TreeNode> genTreeList (int start, int end) {
        List<TreeNode> list = new ArrayList<>(); 
        if (start > end) list.add(null);
        for(int i = start; i <= end; i++) {
            List<TreeNode> leftList = genTreeList(start, i - 1);
            List<TreeNode> rightList = genTreeList(i + 1, end);
            for (TreeNode left : leftList) {
                for(TreeNode right: rightList) {
                    TreeNode root = new TreeNode(i);
                    root.left = left;
                    root.right = right;
                    list.add(root);
                }
            }
        }
        return list;
    }
}
上一篇 下一篇