动态规划-最长公共子序列

(1)、问题描述:给出2个序列,x是从1到m,y是从1到n,找出x和y的最长公共子序列?

x:A B C B D A B

y:B D C A B A

则:最长公共子序列长度为4,BDAB BCAB BCBA均为LCS(最长公共子序列);

wKiom1iq0dHx9O-NAAEByrHMYCU534.png-wh_50

模型实现图:

wKiom1iq0h_hWV7mAACC6DSM76I544.png-wh_50


(2)、问题解决

  代码实现了最长公共子序列的长度

#include<stdio.h>

#define N    10

int LCS(int *a, int count1, int *b, int count2);
int LCS(int *a, int count1, int *b, int count2){
    int table[N][N] = {0};
    int i;
    int j;

    for(i = 0; i < count1; i++){
        for(j = 0; j < count2; j++){
            if(a[i] == b[j]){
                table[i+1][j+1] = table[i][j]+1;
            }else{
                table[i+1][j+1] = table[i+1][j] > table[i][j+1] ? table[i+1][j] : table[i][j+1];
            }
        }
    }

    return table[count1][count2];
}

void main(void){
    int a[] = {1, 2, 3, 4, 5, 6};
    int b[] = {2, 3, 5, 6, 7};
    int count1 = sizeof(a)/sizeof(int);
    int count2 = sizeof(b)/sizeof(int);
    int number;

    number = LCS(a, count1, b, count2);
    printf("%d\n", number);
}

  结果截图

wKiom1iqzs2gKMi9AAAI6PoIdIc156.png-wh_50       


(3)、动态规划的特征:

  特征一(最优子结构的性质):一个问题的最优解包含了子问题的最优解;

  特征二:重叠子问题,一个递归的过程包含很少的独立子问题被反复计算了多次;

  时间复杂度:O(m*n);

 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章