#動態規劃# 子序列個數

題意

求不重複的子序列的個數

Sample Input

4
1 2 3 2

Sample Output

13

思路

dp[i] 表示考慮到第i位的 所有可能數.
1. 如果a[i] 是第一次被使用那麼,dp[i] = dp[i - 1] * 2 + 1. 因爲前面的可以取可以不取.
- 前面不取的話,就是a[i]一個數字。
- 如果前面取的話,那麼a[i] 取不取則有dp[i - 1] * 2種。
2. 如果a[i] 之前已經出現過了。 比如 x1 x2 x3 11 x4 x5 12 那麼 x1 x2 11 和 與 x1 x2 12 應該是同一種。 所以需要減去以11 爲結尾的可能情況,就是dp[prePos]。 而且那個+1也要去掉。

代碼

#include <iostream>
#include <cstring>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <map>
#include <vector>
using namespace std;

int n; 
const int maxn = 1000010;
const int mod = 1e9 + 7;
int a[maxn];
int pos[maxn];
long long dp[maxn];
int main() {
    scanf("%d",&n);
    for(int i = 1;i <= n;i ++) {
        scanf("%d",&a[i]);
    }

    for(int i = 1;i <= n;i ++) {
        if(pos[a[i]] == 0) {
            dp[i] = (dp[i - 1] * 2 + 1) % mod;
        }
        else {
            dp[i] = (dp[i - 1] * 2 - dp[pos[a[i]] - 1] + mod) % mod;
        }
        pos[a[i]] = i;
    }
    cout << dp[n] << endl;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章