您的位置:首页 > 其它

算法设计之DP

2016-01-12 16:12 106 查看

Q1.求回文切割数

1.1问题描述

Given a string s, partition s such that every substring of the partition is a palindrome.Return the minimum cuts needed for a palindrome partitioning of s.

For example, given s = “aab”,Return 1 since the palindrome partitioning [“aa”,”b”] could be produced using 1 cut.

求回文字串的最小分割数。

1.2相关题目

<1>分割1:leetcode

<2>分割2:leetcode

我的超时啦!!还没找到原因!

1.3 其他人的答案

answer:

法一:动态规划: http://www.2cto.com/kf/201503/379759.html

法二:循环递归:http://blog.sina.com.cn/s/blog_70f94db80101jg6f.html

解析:

<1>http://www.hankcs.com/program/cpp/poj-3280-cheapest-palindrome.html

<2>http://www.baidu.com/link?url=c52Kz3tFCltytDGKT0eFEFcwnfzyQJ9P7Yie7i8Aueg0CDm0ZWCz52dh4HGgIYaDZlIgfHgtQWwaiFxMWTUyV_&wd=&eqid=e15bacd40002d3d200000004561dfc33

Q2.买卖股票问题

2.1问题描述

分为以下三种情况:

<1>买一次,卖一次:即为最大子数组和问题:

解法:暴力求解、分治求解、DP求解。

https://expcode.wordpress.com/2015/08/28/given-an-array-of-stock-prices-find-maximum-profit-by-one-transaction-buy-and-sell/

/article/1576672.html

<2>买n次,卖n次:不限制交易次数。

https://siddontang.gitbooks.io/leetcode-solution/content/dynamic_programming/best_time_to_buy_and_sell_stock.html

<3>允许最多两次股票交易:

我的代码:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

2.2 相关题目

<1>1次交易: leetcode

<2>最多两次交易: leetcode

<3>最多k次交易: leetcode

<4>几次交易都可以: leetcode

Q3. Decode Ways

3.1问题描述

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 message “12”, it could be decoded as “AB” (1 2) or “L” (12).The number of ways decoding “12” is 2.Similar as “[LeetCode] Climbing Stairs”. DP. Just add some logic to compare character.

3.2 DP表达式

Transformation function as:

Count[i] = Count[i-1] if S[i-1] is a valid char

or = Count[i-1]+ Count[i-2] if S[i-1] and S[i-2] together is still a valid char.

3.3 伪代码或ac代码

//num[i]表示s[0~i]的译码方式。从序列的最后一个数字考虑,该字符可能被单独译码,也可能与前一个字符联合译码。但有三种特殊情况:
//1.s[i]=='0'时,不能单独译码;2.s[i-1]=='0'时,不能联合译码。3.最后2个数合起来大于26时不能联合译码。故:
/*
if(s[i]=='0') if(s[i]=='0')
{
if(check(s[i-1],s[i]))
num[i]=num[i-2];
else
num[i]=0;
}
else
{
if(check(s[i-1],s[i]))
num[i] = num[i-1]+num[i-2];
else
num[i] = num[i-1];
}

*/
int check(char a,char b);
int numDecodings(char *s)
{

int n=strlen(s);
int num
;
int i;
if(n==0||s[0]=='0')
return 0;
num[0]=1;
if(s[1]=='0')
{
if(check(s[0],s[1]))
num[1]=1;
else
num[1]=0;
}
else
{
if(check(s[0],s[1]))
num[1]=2;
else
num[1]=1;

}

for(i=2;i<n;i++)
{
if(s[i]=='0')
{
if(check(s[i-1],s[i]))
num[i]=num[i-2];
else
num[i]=0;
}
else
{
if(check(s[i-1],s[i]))
num[i] = num[i-1]+num[i-2];
else
num[i] = num[i-1];
}
}
return num[n-1];

}
int check(char a,char b)
{
if((a=='1')||(a=='2'&& b<='6'))
return 1;
else
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: