C语言中自上而下的方法,c – 如何将递归解决方案转换为自下而上或自上而下的解决方案?...

我正在解决这个问题 –

Given a string consisting of a,b and c’s, we can take any two adjacent

distinct characters and replace it with the third character. For

example, if ‘a’ and ‘c’ are adjacent, they can replaced with ‘b’. What

is the smallest string which can result by applying this operation

repeatedly?

现在我编写了以下递归解决方案(远非高效),但希望将其转换为自顶向下或自底向上的解决方案.

问题:我无法想出用于记忆的表格结构.即使我只需输出结果字符串的长度,如何在不实际解决问题的情况下解决它.字符串越来越少,所以如何存储它们?

DP解决方案或Memoization的任何提示都会很棒!

编辑很多人都提出了自上而下的memoization解决方案,请尝试自下而上.

#include

#include

using namespace std;

string reduce(string s)

{

if (s.length() <= 1)

return s;

int k;

char c = s[0];

string min = s;

for (k = 1; k < s.length() && c; ++k)

if (s[k] != c)

c = 0;

if (c)

return s;

if (s.length() == 2){

if (s[0] != 'a' && s[1] != 'a')

s[0] = 'a';

else if (s[0] != 'b' && s[1] != 'b')

s[0] = 'b';

else if (s[0] != 'c' && s[1] != 'c')

s[0] = 'c';

s.resize(1);

return s;

}

for (k = 1; k < s.length(); ++k){

string s1 = reduce(s.substr(0, k));

string s2 = reduce(s.substr(k));

if (s1.length() + s2.length() < min.length())

min = s1 + s2;

if (!s1.empty() && !s2.empty() && s1.back() != s2.front()){

if (s1.back() != 'a' && s2.front() != 'a')

s1.back() = 'a';

else if (s1.back() != 'b' && s2.front() != 'b')

s1.back() = 'b';

else if (s1.back() != 'c' && s2.front() != 'c')

s1.back() = 'c';

s1 = reduce(s1 + s2.substr(1));

if (s1.length() < min.length())

min = s1;

}

}

return min;

}

int main()

{

string input;

cin >> input;

cout << reduce(input) << endl;

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值