【发布时间】:2021-07-19 18:50:25
【问题描述】:
我设法理解了 N-Queens 问题的解决方案,但我对解决方案的时间复杂度有点困惑。我认为整体复杂性将是O(n!*(n^2))。我知道这是错误的。请帮忙。
void placeQueens(int row, vector<int> &columns,int n, vector<vector<int>>&ans)
{
if(row==n)
{
ans.push_back(columns);
return;
}
for(int col=0;col<n;col++)
{
//O(n) time, the checking take O(n) time
if(isSafe(row,col,columns))
{
columns[row]=col;
placeQueens(row+1,columns,n,ans);
}
}
}
bool isSafe(int r1,int c1, vector<int>&columns)
{
//check if r1,c1 is safe to place a queen or not
for(int row=0; row<r1 ; row++)
{
if(columns[row] == c1)
{
//same column
return false;
}
if(abs(columns[row]-c1) == abs(row-r1))
{
//same diagonal
return false;
}
}
return true;
}
根据我的说法,现在的困惑是placeQueens 函数的每个调用都需要O(n^2)。由于有一个for loop 运行n 次,并且在此循环的每次迭代中,我们都会执行O(n) 工作(因为isSafe 函数也需要O(n) 时间。所以整体复杂性变为O(n!*(n^2))。
我知道这是错误的。请帮助我了解我在哪里犯了错误。
【问题讨论】:
-
当使用大 O 时,除了最大的项之外的项往往会被丢弃。
-
是的,但是当它们是相加的时,我们会删除高阶项。就像
O(n!+(n^2))会变成O(n!)。但在这里我们有O(n!*(n^2))。请帮助我了解是否还有其他需要考虑的事项。 -
When using Big O, terms other than the largest tend to be dropped。这是完全正确的。只是,这里只有因子,所以我们不会丢弃任何东西。 -
抱歉之前的回答有误。它不会减少到
O(n^2 * n!)。 它具有T(n) = n*T(n-1) + O(n^2)形式的递归关系,不 简化为O(n^2 * n!)。这是一个链接以获得更多说明:codedope.com/course/algorithms-backtracking
标签: c++ algorithm data-structures time-complexity n-queens