动态规划的学习

/**
*一定要明确dp数组的含义
*
*
*
*
*/

class Solution{
private:
	int arr[10][10];
	int dp[10][10];  //dp数组的含义为对应位置到底部的最大和
	int Length;
public:
	Solution(int Length){
		srand(time(NULL));
		this->Length = Length;
		for (int i = 0; i < Length; ++i){
			for (int j = 0; j <= i; ++j){
				arr[i][j] = rand() % 100;
			}
		}
		for (int i = 0; i < Length; ++i){
			dp[Length - 1][i] = arr[Length - 1][i];
		}
		for (int i = 0; i < Length; ++i){
			for (int j = 0; j <= i; ++j){
				cout << arr[i][j] << " ";			
			}
			cout << endl;
		}
		cout << endl;
		for (int i = 0; i < Length; ++i){
			cout << dp[Length - 1][i] << " ";
		}
		cout << endl << endl;
	}
	int print(){
		for (int i = this->Length-2; i >= 0; --i){
			for (int j = 0; j <= i; ++j){
				dp[i][j] = max(dp[i + 1][j], dp[i + 1][j+1]) + arr[i][j];
			}
		}
		return dp[0][0];
	}
};



/**
 * 比如说对于字符串s1和s2,一般来说都要构造一个这样的 DP table:
 * dp[i-1][j-1]的意思是如果两个字符相同则看其中的str1的上一个字符在到达str2这个位置之前的最长值是多少再在其基础上加一
 * Math.max(dp[i-1][j], dp[i][j-1])的意思是如果两个字符不相等则让它等于它的上一个字符在到达str2这个位置时的
 * 时候的最长值,或者它与这个不相等却与str2的上一个位置的字符相等,因此让其进行最大值的比较
 * 
 */

class Solution{
	 private String str1=" abcgvhfjdfhde";
	 private String str2=" cdesdfghduj";
	 private int dp[][];
	 
	 public Solution() {
		 dp=new int[str1.length()][str2.length()];
		 for(int i=0;i<str1.length();++i) {
			 for(int j=0;j<str2.length();++j) {
				 dp[i][j]=0;
			 }
		 }
	 }
	 
	 public int print() {
		 
		 for(int i=1;i<str1.length();++i) {
			 for(int j=1;j<str2.length();++j) {
				 if(str1.charAt(i)==str2.charAt(j)) {
					 dp[i][j]=dp[i-1][j-1]+1;
				 }
				 else {
					 dp[i][j]=Math.max(dp[i-1][j], dp[i][j-1]);
				 }
			 }
		 }
		 return dp[str1.length()-1][str2.length()-1];
	 }
}

  

原文地址:https://www.cnblogs.com/z2529827226/p/11623630.html