n!
这个算法的应用:从1-9 满足 --- + --- = --- (满足在受限的条件下)
1)使用情况
TSN tsn(4);
tsn.done();
QStringList strList = tsn.result();
int count = strList.size();
qDebug()<<"count="<<count;
foreach ( QString str, strList )
qDebug()<<str;
2)实现代码
class TSN
{
public:
TSN(unsigned n = 1);
~TSN();
unsigned n();
void setN(unsigned n);
void done();
QStringList result();
private:
QVector<int> m_usedStatus;
QVector<int> m_resultVector;
QStringList m_result;
unsigned m_n;
void doStep(int index);
};
TSN::TSN(unsigned n)
{
m_n = n;
}
TSN::~TSN()
{
}
unsigned TSN::n()
{
return m_n;
}
void TSN::setN(unsigned n)
{
m_n = n;
}
void TSN::done()
{
m_result.clear();
m_usedStatus.clear();
m_resultVector.clear();
for( int index = 0; index < m_n; index++)
{
m_usedStatus.append(0);
m_resultVector.append(0);
}
if( m_n == 0 )
m_result<<"0";
else if( m_n == 1 )
m_result<<"1";
else
{
doStep(1);
}
}
void TSN::doStep(int step)
{
int count = m_usedStatus.size();
if( step > count)
{
QStringList strList;
for(int index = 0; index < count; index++)
{
QString str = QString("%1").arg(m_resultVector[index]);
strList<<str;
}
if( strList.length() )
{
QString str = strList.join(",");
m_result<<str;
}
return;
}
for( unsigned index = 1; index <= m_n ; index++ )
{
if( m_usedStatus[index-1] == 0 )
{
m_usedStatus[index-1] = 1;
m_resultVector[step-1] = index;
doStep( step + 1 );
m_usedStatus[index-1] = 0;
}
}
}
QStringList TSN::result()
{
return m_result;
}