如何计算回溯算法的时间复杂度?

46
如何计算这些回溯算法的时间复杂度?它们的时间复杂度是否相同?如果不同,那么它们之间有什么区别?请详细解释,并感谢您的帮助。
1. Hamiltonian cycle:

        bool hamCycleUtil(bool graph[V][V], int path[], int pos) {
            /* base case: If all vertices are included in Hamiltonian Cycle */
            if (pos == V) {
                // And if there is an edge from the last included vertex to the
                // first vertex
                if ( graph[ path[pos-1] ][ path[0] ] == 1 )
                    return true;
                else
                    return false;
            }

            // Try different vertices as a next candidate in Hamiltonian Cycle.
            // We don't try for 0 as we included 0 as starting point in in hamCycle()
            for (int v = 1; v < V; v++) {
                /* Check if this vertex can be added to Hamiltonian Cycle */
                if (isSafe(v, graph, path, pos)) {
                    path[pos] = v;

                    /* recur to construct rest of the path */
                    if (hamCycleUtil (graph, path, pos+1) == true)
                        return true;

                    /* If adding vertex v doesn't lead to a solution, then remove it */
                    path[pos] = -1;
                }
            }

            /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */
            return false;
        }

2. Word break:

       a. bool wordBreak(string str) {
            int size = str.size();

            // Base case
            if (size == 0)
                return true;

            // Try all prefixes of lengths from 1 to size
            for (int i=1; i<=size; i++) {
                // The parameter for dictionaryContains is str.substr(0, i)
                // str.substr(0, i) which is prefix (of input string) of
                // length 'i'. We first check whether current prefix is in
                // dictionary. Then we recursively check for remaining string
                // str.substr(i, size-i) which is suffix of length size-i
                if (dictionaryContains( str.substr(0, i) ) && wordBreak( str.substr(i, size-i) ))
                    return true;
            }

            // If we have tried all prefixes and none of them worked
            return false;
        }
    b. String SegmentString(String input, Set<String> dict) {
           if (dict.contains(input)) return input;
           int len = input.length();
           for (int i = 1; i < len; i++) {
               String prefix = input.substring(0, i);
               if (dict.contains(prefix)) {
                   String suffix = input.substring(i, len);
                   String segSuffix = SegmentString(suffix, dict);
                   if (segSuffix != null) {
                       return prefix + " " + segSuffix;
                   }
               }
           }
           return null;
      }


3. N Queens:

        bool solveNQUtil(int board[N][N], int col) {
            /* base case: If all queens are placed then return true */
            if (col >= N)
                return true;

            /* Consider this column and try placing this queen in all rows one by one */
            for (int i = 0; i < N; i++) {
                /* Check if queen can be placed on board[i][col] */
                if ( isSafe(board, i, col) ) {
                    /* Place this queen in board[i][col] */
                    board[i][col] = 1;

                    /* recur to place rest of the queens */
                    if ( solveNQUtil(board, col + 1) == true )
                        return true;

                    /* If placing queen in board[i][col] doesn't lead to a solution then remove queen from board[i][col] */
                    board[i][col] = 0; // BACKTRACK
                }
            }
        }

我有些困惑,因为单词拆分的复杂度是O(2n),但汉密尔顿回路、打印相同字符串的不同排列和解决N皇后问题的复杂度都不同。


3
如果你把重点放在实际的回溯(或者更确切地说,在每一步的分支可能性上),你只会看到指数级的复杂度。然而,如果回溯要探索的状态数量有限,那么它只能探索这些状态。如果你确保算法只访问每个可能的状态一次(并且每个状态的时间是恒定的),那么需要探索的可能状态的数量现在就是时间复杂度的上限——不管你的算法是否使用回溯。 - user180247
2个回答

57

简而言之:

  1. 哈密尔顿回路:最坏情况下为O(N!)
  2. 单词拆分和字符串分段:O(2^N)
  3. N皇后问题:O(N!)

注:对于单词拆分,存在一个O(N^2)的动态规划解决方案。


更多细节:

  1. 在哈密尔顿回路中,每次递归调用都会选择剩余顶点中的一个最坏情况。在每个递归调用中,分支因子减少1。在这种情况下,递归可以被认为是n个嵌套循环,在每个循环中,迭代次数减少1。因此,时间复杂度由以下公式给出:

    T(N) = N*(T(N-1) + O(1))
    T(N) = N*(N-1)*(N-2).. = O(N!)

  2. 类似地,在N皇后问题中,每次分支因子减少1或更多,但不多,因此上限为O(N!)

  3. 对于单词拆分,情况更为复杂,但我可以给你一个近似的想法。在单词拆分中,字符串的每个字符在最坏的情况下都有两种选择,要么成为前一个单词的最后一个字母,要么成为新单词的第一个字母,因此分支因子为2。因此,对于单词拆分和字符串分段,T(N) = O(2^N)


请详细解释并区分单词拆分问题的B部分和A部分的时间复杂度。 - da3m0n
抱歉,我的第一个答案错误地估计了WordBreak的时间复杂度。 - Vikram Bhat

13

回溯算法:

n皇后问题:O(n!)

图着色问题:O(nm^n)//其中n为顶点数,m为使用的颜色数

哈密顿回路:O(N!)

单词拆分和字符串分段:O(2^N)

子集求和问题:O(nW)


1
使用回溯算法解决子集和问题的复杂度不应该是[O(2^(N/2))](https://en.wikipedia.org/wiki/Subset_sum_problem#Exponential_time_algorithm)吗? - Kewal Shah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接