【问题标题】:N Queens problem solution from Cracking the Coding Interview. What would be the Time Complexity?Cracking the Coding Interview 中的 N Queens 问题解决方案。时间复杂度是多少?
【发布时间】: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


【解决方案1】:

你是正确的,它对每次调用 placeQueens 都有效 O(n2),但因为它只对 safe 方格进行递归调用,而不会' t 与之前的任何冲突,远少于 n!拨打电话。

顶层调用会尝试顶行的每个方格并进行 n 次递归调用,但如果 n 非常大,那么第一个方格的几乎所有选择都将排除 3 选择下一行,而不是 1。同样,在第二行的几乎所有选择之后,6 个方格将被排除在第三行。

如果 C(n) 是 nxn 板的调用次数,那么 C(n) 将不会离 n(n-3)(n-6) 太远...

当然我们有 C(n) 比任何多项式都快。

因此,只要每次调用 placeQueens 完成多项式工作,那么复杂度肯定在 O(n!) 以内。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多