zoukankan      html  css  js  c++  java
  • 出栈次数的DFS计算

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <stack>
    #define N 24
    
    bool stored[N + 2];
    int ansCount;
    
    using namespace std;
    void print(stack<int> s)
    {
        cout << "stackSize="<<s.size()<< "  ";
        while(!s.empty())
        {
            int temp = s.top();
            s.pop();
            cout << "stac[i]=" << temp<<"  "; 
        }
        cout << endl;
    }
    
    void DFS(int curNum, const int maxNum, stack<int> s)//curNum表示1-curNum-1已经放入了栈中,curNum没有,本层递归结束的时候,curNum一定入栈中 
    {
        //print(s); 
        if (curNum > maxNum)//结束 
        {
            //cout << "curNum="<<curNum<<endl;
            //for(int i=maxNum;i>=1;i--) cout<<" "<<stored[i];
            //cout << endl;
            bool allStored = true;
            for (int i = maxNum; i >= 1; i--)
                if (!stored[i])
                    allStored = false;
            if (allStored)// 类似cur==n的功能 
            {
                ansCount += 1;
                return;
            }
            return;//结束 
        }
        else//可以继续放数的情况,说明栈中不为空,存有数据,可以对数据进行出栈操作  | 存数的操作 
        {
            //s.push(curNum);
            //stored[curNum] = true;//可以省略 
            /* 
            if (stored[curNum])
            {
                DFS(curNum + 1, maxNum, s);
            }
            else if (!s.empty())
            {
                s.pop();
                DFS(curNum, maxNum, s);
            }
            */
            stored[curNum]=true;
            while(true)
            {
                s.push(curNum);//进栈一个数 
                DFS(curNum+1,maxNum,s);
                s.pop();
                if(!s.empty()) s.pop();//出栈一个数
                else break; 
            }
        }
    }
    
    int main(int argc, char** argv)
    {
        stack<int> s;
        int m;
        cin >> m;
        DFS(1,m,s);
        cout << ansCount << endl;
        system("pause");
        return 0;
    }
  • 相关阅读:
    java去掉List中的重复值代码
    jquery 请求jsp传递json数据的方法
    jsp自定义标签分析
    jquery mouseout事件冒泡解决方法
    java split函数 对空的处理
    log4j使用感受
    mysql数据库主外键级联删除脚本RESTRICT --> CASCADE
    jquery 实现层级下拉框联动效果 代码
    JSP图片上传 公共工具类
    Apache和Nginx的对比
  • 原文地址:https://www.cnblogs.com/zuimeiyujianni/p/9777234.html
Copyright © 2011-2022 走看看