被C++中的矩阵绊倒

Stumped by Matrix in C++

本文关键字:C++      更新时间:2023-10-16

我有一个看似简单的问题,但就我的一生而言,我无法解决。基本上,我要寻找的是如何找到非对称矩阵的所有排列,其中某些值必须保持在某些位置。解释这一点最简单的方法是用一个例子。。。

假设我们有以下内容。。。

a b c
a
b c
d e f

在这个矩阵中,我们必须找到所有的排列,其中第一个字母是"a"、"b"或"c",第二个字母是"a",第三个字母是b"或"c",第四个字母是d"、e"或"f"。在我们的算法中,矩阵的大小是未知的。它也可以是…

a
b
c
d

或者。。。

a b c d
e f g h
i j k l
m n o p

在我的第一个例子中,我可以通过观察看到,可能性是:

aabd
aabe
aabf
aacd
aace
aacf
babd
babe
babf
bacd
bace
bacf
cabd
cabe
cabf
cacd
cace
cacf

然而,我就是搞不懂算法。有人能帮我理清思路吗?如果我提前知道尺码,我可以做,但我没有。我觉得递归函数就是答案,但我就是看不出来

编辑:这是我到目前为止将值转换为矩阵的代码。在某些情况下,该值是独立的,而在另一些情况下,它以多个值的集合形式出现,由括号包围。。。

int CountTestCases(const string &iTestStr, const map<string::size_type, string::size_type> &iHashTable)
{
vector<vector<char>> charMatrix;
string::const_iterator strIt = iTestStr.begin();
while(strIt != iTestStr.end())
{
if(*strIt == '(')
{
++strIt;
char c = *strIt;
vector<char> tmpVec;
tmpVec.push_back(c);
++strIt;
while(*strIt != ')')
{
c = *strIt;
tmpVec.push_back(c);
++strIt;
}
charMatrix.push_back(tmpVec);
}
else
{
char c = *strIt;
vector<char> tmpVec;
tmpVec.push_back(c);
charMatrix.push_back(tmpVec);
}
++strIt;
}
return 0;
}

这里是伪代码:

int main()
{    
vector<char> outputVec;
PassToNextLevel(0, outputVec); 
}

function PassToNextLevel(int rowId, vector<char) outputVec)
{
for each char 'currChar' in the 'charMatrix[rowId]'
{ 
outputVec.push_back(currChar);
PassToNextLevel(rowId++, outputVec); // recursive call, pass by value
if(rowId == rowSize-1) { // last row
print outputVec; 
}
}     
}

将数据存储为vector<vector<char>>—您总是可以向vector添加更多内容,这样您就不需要知道之前的大小。

是的,你需要做一个递归。在每个级别上,您都可以从对应于该级别的向量中选择一个元素,并递归调用下一个级别。当你用完向量时,你就有了一个解决方案。

哇,我做到了!这是我想出的函数。。。

void FindCartisian(const vector<vector<char>> &iCharMatrix, int iRow, string &iWord, vector<string> &iFinalWords)
{
//We've reached the end of the column, save the finished product and return
if(iRow + 1 > iCharMatrix.size())
{
iFinalWords.push_back(iWord);
return;
}
//Iterate across the row
for(vector<char>::const_iterator it = iCharMatrix[iRow].begin(); it != iCharMatrix[iRow].end(); ++it)
{
//Append what is in this position
char c = *it;
iWord.append(1, c);
//Drill down recursively from here
FindCartisian(iCharMatrix, iRow + 1, iWord, iFinalWords);
//Erase the last thing we added
iWord.erase(iWord.end() - 1);
}
}

我突然想到,我可以使用char堆栈而不是字符串,但由于最终产品无论如何都必须是字符串,所以在最后将堆栈转换为字符串似乎相当麻烦。

对于大型数据集来说,这是非常缓慢的。关于如何让它更快,有什么想法吗?

相关文章:
  • 没有找到相关文章