Why I get a TLE? Please help me find out the error!


  • -1
    W
    class Solution {
    public:
        int totalNQueens(int n) {
            int result=0;
            int *A=new int[n+1];
            backTrack(1,n,A,result);
            delete[] A;
            return result;
        }
        void backTrack(int first,int last,int A[],int &result){
            if(first>last){
                ++result;
            }
            for(int i=1;i<=last;++i){
                A[first]=i;
                if(legalPosition(first,A)){
                    backTrack(first+1, last, A, result);
                }
            }
        }
        bool legalPosition(int k,int A[]) {
            //判断前k个QUEEN的位置时候合法
            for(int i=1;i<=k-1;++i){
                if(A[k]==A[i]||abs(k-i)==abs(A[k]-A[i])){
                return false;
                }
            }
            return true;
        }
    };

  • 0
    Z

    No return in backTrack. Additionally, you'd better use English words for the annotation instead of Chinese words, although I understand the sentence.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.