LeetCode:Shortest Common Supersequences

dp:

#include<bits/stdc++.h>

using namespace std;

void printVec1(vector<int>& v);
void printVec2(vector<vector<int>>& v);

class Solution {
public:
    string shortestCommonSupersequence(string str1, string str2) {
        int L1 = str1.length();
        int L2 = str2.length();
        int dp[1005][1005];
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=L1;i++){
            char c1 = str1[i-1];
            for(int j=1;j<=L2;j++){
                char c2 = str2[j-1];
                dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
                if(c1 == c2){
                    dp[i][j] = max(dp[i][j],dp[i-1][j-1] + 1);
                }
            }
        }
        int x = L1;
        int y = L2;
        int cnt = L1 + L2;
        string ans = "";
        while(cnt>0){
            if(y > 0 && dp[x][y] == dp[x][y-1]){
                y--;
                ans = str2[y] + ans;
                cnt --;
            }else if(x > 0 && dp[x][y] == dp[x-1][y]){
                x--;
                ans = str1[x] + ans;
                cnt --;
            }else{
                y--;
                x--;
                ans = str1[x] + ans;
                cnt -= 2;
            }
        }
        return ans;
    }
};

int main(){
    Solution myS;
    string ans = myS.shortestCommonSupersequence("a","a");
    cout<<ans<<endl;
    return 0;
}

// 输出一维数组
void printVec1(vector<int>& v){
    printf("{");
    if(v.size()!=0) printf("%d",v[0]);
    for(int i=1;i<v.size();i++){
        printf(",%d",v[i]);
    }
    printf("}");
}

// 输出二维数组
void printVec2(vector<vector<int>>& v){
    printf("{");
    if(v.size()!=0) printVec1(v[0]);
    for(int i=1;i<v.size();i++){
        printf(",");
        printVec1(v[i]);
    }
    printf("}");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值