52. N-Queens II

来源:互联网 发布:软件测试做什么 编辑:程序博客网 时间:2024/05/21 16:15

和上一个题是一样的。

还是在写isValid函数的时候出错,while里面忘了写=

class Solution {public:    int totalNQueens(int n) {        vector<string> v(n, string(n, '.'));        int res = 0;        helper(v, n, 0, res);        return res;    }    void helper(vector<string>& v, int n, int i, int& res){        if(i == n){            res++;            return;        }        for(int j = 0; j < n; ++j){            v[i][j] = 'Q';            if(isValid(v, n, i, j) == true)                helper(v, n, i+1, res);            v[i][j] = '.';        }    }    bool isValid(vector<string>& v, int n, int i, int j){        for(int row = 0; row < i; ++row){            if(v[row][j] == 'Q')                    return false;        }        int x = i-1, y = j-1;        while(x >= 0 && y >= 0){            if(v[x][y] == 'Q')  return false;            x--;            y--;        }        x = i - 1, y = j + 1;        while(x >= 0 && y < n){            if(v[x][y] == 'Q')  return false;            x--;            y++;        }        return true;            }};


原创粉丝点击