[LeetCode] Dp】的更多相关文章

https://leetcode.com/problems/k-inverse-pairs-array/description/ [题意] 给定n和k,求正好有k个逆序对的长度为n的序列有多少个,0<=k<=1000, 1<=n<=1000,答案模1e9+7 [思路] dp[i][j]表示正好有j个逆序对的长度为i的序列的方案数,最终我们要求的就是dp[n][k] 考虑dp[i+1][j]和dp[i][j]的关系,长度为i+1的序列相当于在长度为i的序列中插入一个数,那么有 xxx…
https://leetcode.com/problems/palindrome-partitioning-ii/description/ [题意] 给定一个字符串,求最少切割多少下,使得切割后的每个子串都是回文串 [思路] 求一个字符串的所有子串是否是回文串,O(n^2) dp从后往前推 vector<vector<bool> > p(len,vector<bool>(len)); ;i<len-;i++){ ;j<len-;j++){ if(j!=i)…
https://leetcode.com/problems/dungeon-game/description/ [题意] 给定m*n的地牢,王子初始位置在左上角,公主在右下角不动,王子要去救公主,每步只能往右或往下走一格.每个格子是一个整数,负数代表生命值减掉相应分数,正数表示生命值增加相应分值,要保证王子在走的过程中不挂掉,即经过每个格子后的生命值大于等于1,问王子最初的生命值最少是多少. [思路] 倒着推dp,计算(i,j)->(m,n)的可生存血量. dp[i][j]=max(1,min(…
Best Time to Buy and Sell Stock 题目: Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algori…
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers…
计算最少用多少不把word1变为word2, 思路:建立一个dp表,行为word1的长度,宽为word2的长度 1.边界条件,dp[i][0] = i,dp[0][j]=j 2.最优子问题,考虑已经知道word1[0:i-1]转变为word2[0:j-1]的次数,只需要考虑word1[i]和word[j]的情况 3.子问题重叠,word1[i]和word2[j]是否相等,每种情况下怎样有最少步骤 class Solution(object): def minDistance(self, word…
A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example,Given encoded…
一个m*n的表格,每个格子有一个非负数,求从左上到右下最短的路径值 和62,63两个值是同一个思路,建立dp表,记录每个位置到右下角的最短路径的值 class Solution(object): def minPathSum(self, grid): m,n = len(grid),len(grid[0]) flag = [[0 for i in range(n)] for j in range(m)] flag[m-1][n-1] = grid[m-1][n-1] for i in range…
Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. For example, There is one obstacle in the middl…
1. 动态规划的适用场景 动态规划常常适用于有重叠子问题和最优子结构性质的问题,动态规划方法所耗时间往往远少于朴素解法. 2. 动态规划的基本思想 动态规划背后的基本思想非常简单.大致上,若要解一个给定问题,我们需要解其不同部分(即子问题),再合并子问题的解以得出原问题的解.通常许多子问题非常相似,为此动态规划法试图仅仅解决每个子问题一次,从而减少计算量:一旦某个给定子问题的解已经算出,则将其记忆化存储,以便下次需要同一个子问题解之时直接查表.这种做法在重复子问题的数目关于输入的规模呈指数增长时…