【LEETCODE】68、分治递归,medium级别,题目:95、120、91

package y2019.Algorithm.dynamicprogramming.medium;

/**
 * @ProjectName: cutter-point
 * @Package: y2019.Algorithm.dynamicprogramming.medium
 * @ClassName: NumDecodings
 * @Author: xiaof
 * @Description: 91. Decode Ways
 * A message containing letters from A-Z is being encoded to numbers using the following mapping:
 *
 * ‘A‘ -> 1
 * ‘B‘ -> 2
 * ...
 * ‘Z‘ -> 26
 * Given a non-empty string containing only digits, determine the total number of ways to decode it.
 *
 * Example 1:
 *
 * Input: "12"
 * Output: 2
 * Explanation: It could be decoded as "AB" (1 2) or "L" (12).
 * Example 2:
 *
 * Input: "226"
 * Output: 3
 * Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
 * @Date: 2019/8/15 8:54
 * @Version: 1.0
 */
public class NumDecodings {

    public int solution(String s) {
        if (s == null || s.equals("") || (s.length() == 1 && s.equals("0"))) {
            return 0;
        }
        //我们发现这个串总最多一次可以使用2个字符,并且这两个字符组成的数要小于26或等于26才行
        //那么我们可以发先要获取当前字符能组成的解码数可分为
        //dp[n] = dp[n-1] + {if(2num <= 26}{dp[n-2} 只有满足使用最后2位数作为解码数字的时候才能加上不用这个2个字符可以组成的个数
        int[] dp = new int[s.length() + 1];
        dp[0] = 1;dp[1] = 1;
        char[] sc = s.toCharArray();

        for (int i = 2; i < dp.length; ++i) {
            //i用来标识取s的前i个字符,还要判断这个字符不能是0,不然不能单个字符使用
            if (sc[i - 1] != ‘0‘) {

                dp[i] = dp[i - 1];
            }
            //判断如果去除2个数的位置
            int l = i - 2;
            int value = Integer.valueOf(s.substring(l, i));
            if (value <= 26 && value > 0) {
                dp[i] += dp[i - 2];
            }
        }
        return dp[s.length()];
    }

    public static void main(String[] args) {
        String s = "12";
        String s2 = "226";
        String s3 = "10";

        NumDecodings fuc = new NumDecodings();

        fuc.solution(s3);

    }
}
package y2019.Algorithm.dynamicprogramming.medium;

import java.util.List;

/**
 * @ProjectName: cutter-point
 * @Package: y2019.Algorithm.dynamicprogramming.medium
 * @ClassName: MinimumTotal
 * @Author: xiaof
 * @Description: 120. Triangle
 * Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
 *
 * For example, given the following triangle
 *
 * [
 *      [2],
 *     [3,4],
 *    [6,5,7],
 *   [4,1,8,3]
 * ]
 * The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
 * @Date: 2019/8/15 8:54
 * @Version: 1.0
 */
public class MinimumTotal {

    public int solution(List<List<Integer>> triangle) {
        //这题我们反向遍历,从底往上进行遍历最小值
        //可以得知第k行第i个数的最小路径是minpath[k][i]=min{minpath[k+1][i], minpath[k+1][i+1]} + triangle[k][i]
        int[][] minpath = new int[triangle.size() + 1][triangle.size() + 1];
        for (int row = triangle.size() - 1; row >= 0; --row) {
            //列遍历数据
            for (int column = 0; column < triangle.get(row).size(); ++column) {
                minpath[row][column] = Math.min(minpath[row + 1][column], minpath[row + 1][column + 1]) + triangle.get(row).get(column);
            }
        }

        return minpath[0][0];
    }
}
package y2019.Algorithm.dynamicprogramming.medium;

import y2019.Algorithm.common.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: cutter-point
 * @Package: y2019.Algorithm.dynamicprogramming.medium
 * @ClassName: GenerateTrees
 * @Author: xiaof
 * @Description: 95. Unique Binary Search Trees II
 *
 * Given an integer n, generate all structurally unique BST‘s (binary search trees) that store values 1 ... n.
 *
 * Example:
 *
 * Input: 3
 * Output:
 * [
 *   [1,null,3,2],
 *   [3,2,null,1],
 *   [3,1,null,null,2],
 *   [2,1,3],
 *   [1,null,2,null,3]
 * ]
 * Explanation:
 * The above output corresponds to the 5 unique BST‘s shown below:
 *
 *    1         3     3      2      1
 *     \       /     /      / \       *      3     2     1      1   3      2
 *     /     /       \                  *    2     1         2                 3
 *
 * @Date: 2019/8/15 8:54
 * @Version: 1.0
 */
public class GenerateTrees {

    public List<TreeNode> solution(int n) {

        if (n == 0) return new ArrayList<>();

        return backtruack(1, n);
    }

    //因为要求出所有可能性,那么需要递归出所有结果
    public List<TreeNode> backtruack(int l, int r) {
        //我们需要进行操作的范围是l->r
        List<TreeNode> res = new ArrayList<>();
        //如果l>r超过了,那么直接返回一个空的集合,因为这个区间不可能组成一颗树
        if (l > r) {
            res.add(null);
            return res;
        }
        //如果l == r 那么就返回以当前节点作为根的树
        if (l == r) {
            res.add(new TreeNode(l));
            return res;
        }
        //其余情况把l->r的所有节点进行遍历,依次作为根节点进行组合
        List<TreeNode> leftlist, rightlist;
        for (int i = l; i <= r; ++i) {
            //依次吧第i个数作为根的时候值
            leftlist = backtruack(l, i - 1);
            rightlist = backtruack(i + 1, r);

            //最后吧这两个值都组合起来
            for (TreeNode lefttree : leftlist) {
                for (TreeNode righttree : rightlist) {
                    TreeNode root = new TreeNode(i); //当前根节点
                    root.left = lefttree;
                    root.right = righttree;
                    res.add(root);
                }
            }
        }

        return res;
    }
}

原文地址:https://www.cnblogs.com/cutter-point/p/11359631.html

时间: 2024-07-31 17:51:28

【LEETCODE】68、分治递归,medium级别,题目:95、120、91的相关文章

[LeetCode] 039. Combination Sum (Medium) (C++)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 039. Combination Sum (Medium) 链接: 题目:https://leetcode.com/problems/combination-sum/ 代码(github):https://github.com/illuz/leetcode 题意: 给出一些正整数集合,以及一个目标数,从集合中选择一

[array] leetcode - 39. Combination Sum - Medium

leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from

LeetCode --- 68. Text Justification

题目链接:Text Justification Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you

[LeetCode] 031. Next Permutation (Medium) (C++/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 031. Next Permutation (Medium) 链接: 题目:https://oj.leetcode.com/problems/next-permutation/ 代码(github):https://github.com/illuz/leetcode 题意: 求一个序列的下一个排列. 分析: 可以用

LeetCode OJ平台上Maximum Subarray题目O(n)复杂度解决方案

原始题目如下,意为寻找数组和最大的子串,返回这个最大和即可. Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [?2,1,?3,4,?1,2,1,?5,4], the contiguous subarray [4,?1,2,1] has the largest sum = 6.

LeetCode OJ平台上Sort Colors题目算法探讨

原题如下,意思就是说无序数组(由0,1,2组成),一遍扫描,把数组整理成若干个0-若干个1-若干个2这样的序列. Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integ

DVWA系列之4 利用SQLMap进行medium级别注入

下面我们尝试利用SQLMap进行medium级别下的注入. 首先探测是否存在注入点,执行下面的命令: sqlmap.py -u http://192.168.80.1/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit 检测结果没有发现注入点,这是由于DVWA需要先登录然后才能使用,因而这里需要得到当前会话的cookie,用来在渗透过程中维持连接状态.利用Burpsuite拦截数据包,获取cookie. 在SQLMap中加--cookie参数,继续进行注入

分治递归:求数组元素的最大值,最小值

//分治递归,求数组元素的最大值,最小值 /** * 保存产生的最大值,最小值 * @author Administrator * */ public class Values { private int max; private int min; public Values(int max,int min){ this.max=max; this.min=min; } public int getMax() { return max; } public void setMax(int max)

DVWA系列之23 medium级别上传漏洞分析与利用

下面再来分析medium级别的代码: 这里分别通过"$_FILES['uploaded']['type']"和"$_FILES['uploaded']['size']"获取了上传文件的 MIME类型和文件大小. MIME类型用来设定某种扩展名文件的打开方式,当具有该扩展名的文件被访问时,浏览器会自动使用指定的应用程序来打开,如jpg图片的MIME为image/jpeg. 因而medium与low的主要区别就是对文件的MIME类型和文件大小进行了判断,这样就只允许上传

归并排序 分治+递归

0      1    2     3     4     5     6     7     8   //下标 {  9  ,  4  ,  3  ,  7  ,  3  ,  8  ,  2  ,  4  ,  8  }//通过mergesort函数递归 来切 开始的时候fir=0, las=8, mid=4  所以下标0-4,分为前组   5-8分为后组 {  9  , 4   ,  3  ,  7  ,  3 }{ 8   , 2   , 4  ,  8  } {  9   , 4  ,