推箱子,递归与递推

递推代码

 1 #include <vector>
 2 #include <iostream>
 3 #include <stack>
 4 using namespace std;
 5 
 6 const int MAX = 100000000;
 7 int h[MAX] = { 0 };
 8 int pre[MAX] = {0};
 9 //用于累计count,如果某个位置有比之前某一个数大的,则比较这个位置的count与之前的数的count的关系 
10 int count[MAX] = { 0 };
11 
12 int main()
13 {
14     int n;
15     cin >> n;
16 
17     for (int i = 0;i<n;i++)
18     {
19         cin >> h[i];
20     }
21     
22     fill(count,count+MAX,1); 
23     
24     for(int i=0 ;i<MAX;i++)
25     {
26         pre[i] = i;
27     }
28     
29     //记录最长的子串 
30     int max = 0;
31     //记录最长字串的最大的一个值 
32     int maxid = 0;
33     
34     for(int i=1;i<n;i++)
35     {
36         //每次遍历,如果大则取最大的count 
37         for(int j=i-1;j>=0;j--)
38         {
39             if(h[i] > h[j] && count[i] < count[j] + 1 )
40             {
41                 count[i] = count[j] + 1;
42                 
43                 pre[i] = j;
44     
45                 if(max < count[i])
46                 {
47                     maxid = i;
48                     max = count[i];
49                 }
50              } 
51         }
52     }
53     
54     cout << max << endl;
55 
56     //输出该子串 
57     while(maxid != pre[maxid])
58     {
59         cout << h[maxid] << " ";
60         maxid = pre[maxid];
61     }
62     cout << h[maxid] << endl;
63     
64     return 0;
65 }

递归实现

#include <vector>
#include <iostream>
#include <stack>
using namespace std;

const int MAX = 100000000;
int h[MAX] = {0};

int num;

stack<int> tmp;
stack<int> res;
stack<int> res1;

int maxh = 0;

void solve(int *h,int &num,int pos,int len)
{

    if(pos == len)
    {
        
        if(tmp.size() > num)
        {
            res = tmp;
            num = tmp.size();
        }
        return;
    }
    
    for(int i=pos;i<len;i++)
    {
        if(h[i] > maxh)
        {
            
            //添加进去 
            maxh = h[i];
            tmp.push(h[i]);
            solve(h,num,pos+1,len);
            //回溯 
            tmp.pop();
            if(tmp.size() > 0)
            {
                maxh = tmp.top(); 
            } 
            else
            {
                maxh = 0;
            }
            
            //不添加进去 ,注意递归的下一次位置 
            solve(h,num,pos+1,len);
        }
        else
        {
            solve(h,num,pos+1,len);
        }
    
    }
}

int main()
{
    int n;
    cin >> n;
    
    for(int i=0;i<n;i++)
    {
        cin >> h[i];
    }
    
    int num = 0;
    
    solve(h,num,0,n);
    cout << num << endl;
    
    while(!res.empty())
    {
        cout << res.top();
        res.pop();
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xiaochi/p/10409947.html