leetcode N-Queens/N-Queens II, backtracking, C++

thanks to the video of stanford cs106b lecture 10 by Julie Zelenski for the nice explanation of recursion and backtracking, highly recommended.

//N-Queens(12ms)

class Solution {
    vector<vector<string>> ans;
    int N;
    //int numofsol;

    void AddTo_ans(string &conf) {
        vector<string> vecstrtmp;
        string strtmp(N,‘.‘);
        for(auto ind: conf) {
            vecstrtmp.push_back(strtmp);
            vecstrtmp.back()[(size_t)ind-1]=‘Q‘;
        }
        ans.push_back(vector<string>());
        ans.back().swap(vecstrtmp);
    }
    void RecListNQueens(string soFar, string rest) {
        if(rest.empty()) {
            //++numofsol;
            AddTo_ans(soFar);
        }
        else {
            int i,j,len=soFar.size(), flag;
            for(i=0;i<rest.size();++i) {
                for(j=0;j<len;++j) {
                    flag=1;
                    if(soFar[j]-rest[i]==len-j || soFar[j]-rest[i]==j-len) {
                        flag=0; break;
                    }
                }
                if(flag) RecListNQueens(soFar+rest[i],rest.substr(0,i)+rest.substr(i+1));
            }
        }
    }
public:
    vector<vector<string>> solveNQueens(int n) {
        ans.clear();
        //numofsol=0;
        N=n;
        string str;
        for(int i=1;i<=n;++i) str.push_back(i);
        RecListNQueens("", str);
        return ans;
    }
};

//with a tiny modification,

//N-Queens II (8ms)

class Solution {
    //vector<vector<string>> ans;
    int N;
    int numofsol;

    /*void AddTo_ans(string &conf) {
        vector<string> vecstrtmp;
        string strtmp(N,‘.‘);
        for(auto ind: conf) {
            vecstrtmp.push_back(strtmp);
            vecstrtmp.back()[(size_t)ind-1]=‘Q‘;
        }
        ans.push_back(vector<string>());
        ans.back().swap(vecstrtmp);
    }*/
    void RecListNQueens(string soFar, string rest) {
        if(rest.empty()) {
            ++numofsol;
            //AddTo_ans(soFar);
        }
        else {
            int i,j,len=soFar.size(), flag;
            for(i=0;i<rest.size();++i) {
                for(j=0;j<len;++j) {
                    flag=1;
                    if(soFar[j]-rest[i]==len-j || soFar[j]-rest[i]==j-len) {
                        flag=0; break;
                    }
                }
                if(flag) RecListNQueens(soFar+rest[i],rest.substr(0,i)+rest.substr(i+1));
            }
        }
    }
public:
    int totalNQueens(int n) {
        //ans.clear();
        numofsol=0;
        N=n;
        string str;
        for(int i=1;i<=n;++i) str.push_back(i);
        RecListNQueens("", str);
        return numofsol;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-27 17:51:17

leetcode N-Queens/N-Queens II, backtracking, C++的相关文章

Java [Leetcode 119]Pascal&#39;s Triangle II

题目描述: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3,3,1]. 解题思路: 每次在上一个list前面插入1,然后后面的每两个间相加赋值给前一个数. 代码描述: public class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> r

leetcode 【 Pascal&#39;s Triangle II 】python 实现

题目: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3,3,1]. Note:Could you optimize your algorithm to use only O(k) extra space? 代码:oj测试通过 Runtime: 48 ms 1 class Solution: 2 # @return a list of intege

[LeetCode] Unique Binary Search Trees II (难以忍受的递归)

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example, Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3 class Solution { private

leetcode 119 Pascal&#39;s Triangle II ----- java

Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3,3,1]. Note:Could you optimize your algorithm to use only O(k) extra space? 上一道题的延伸版,就是直接求出第k行的数,要求用o(k)的空间复杂度. 也是直接相加就可以了. public class Solution { pub

leetCode 119. Pascal&#39;s Triangle II 数组

119. Pascal's Triangle II Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3,3,1]. Note:Could you optimize your algorithm to use only O(k) extra space? 代码如下:(使用双数组处理,未优化版) class Solution { public:     

LeetCode#119 Pascal&#39;s Triangle II

Problem Definition: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? Solution: 1 def getRow(rowIndex): 2 pt=[] 3 for rn in

[leetcode] 2. Pascal&#39;s Triangle II

我是按难度往下刷的,第二道是帕斯卡三角形二.简单易懂,题目如下: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? 就是输入k然后输出第k行帕斯卡三角[其实我一直把它叫杨辉三角]. 我这边思路是拿

[LeetCode 题解]: Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up:Can you solve it without using extra space? 题意: 给定一个链表,找到环起始的位置.如果环不存在,返回NULL. 分析: (1)首先要判断该链表是否有环.如果没有环,那么返回NULL. (2)其次,当已知环存在后,寻找环起始的位置. 思路: (

LeetCode OJ - Reverse Linked List II

题目: Reverse a linked list from position m to n. Do it in-place and in one-pass. For example:Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note:Given m, n satisfy the following condition:1 ≤ m ≤ n ≤ l

[leetcode]Unique Binary Search Trees II @ Python

原题地址:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ 题意:接上一题,这题要求返回的是所有符合条件的二叉查找树,而上一题要求的是符合条件的二叉查找树的棵数,我们上一题提过,求个数一般思路是动态规划,而枚举的话,我们就考虑dfs了.dfs(start, end)函数返回以start,start+1,...,end为根的二叉查找树. 代码: # Definition for a binary tree node #