java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java C++ 不同的子序列

Java C++题解eetcode940不同的子序列 II

作者:AnjaVon

这篇文章主要为大家介绍了Java C++题解eetcode940不同的子序列 II实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

题目要求

思路一:动态规划+转移优化

Java

class Solution {
    public int distinctSubseqII(String s) {
        int MOD = (int)1e9+7;
        int res = 0;
        int[] f = new int[26];
        for (int i = 0; i < s.length(); i++) {
            int cur = s.charAt(i) - 'a', pre = f[cur];
            f[cur] = (res + 1) % MOD;
            res = ((res + f[cur] - pre) % MOD + MOD) % MOD;
        }
        return res;
    }
}

C++

class Solution {
public:
    int distinctSubseqII(string s) {
        int MOD = (int)1e9+7;
        int res = 0;
        int f[26];
        memset(f, 0, sizeof(f));
        for (int i = 0; i < s.size(); i++) {
            int cur = s[i] - 'a', pre = f[cur];
            f[cur] = (res + 1) % MOD;
            res = ((res + f[cur] - pre) % MOD + MOD) % MOD;
        }
        return res;
    }
};

Rust

impl Solution {
    pub fn distinct_subseq_ii(s: String) -> i32 {
        let MOD = 1000000007;
        let mut res = 0;
        let mut f = vec![0; 26];
        for cur in s.chars() {
            let i = cur as u8 - 'a' as u8;
            let pre = f[i as usize];
            f[i as usize] = (res + 1) % MOD;
            res = ((res + f[i as usize] - pre) % MOD + MOD) % MOD;
        }
        res
    }
}

思路二:求和(调api)

栗子【vonvv】:

当前遍历字符f[i]子串
v1v
o2vo,o
n4vn,von,on,n
v8vv,vov,ov,vnv,vonv,onv,nv,v
v15vv,vov,ov,vnv,vonv,onv,nv,vvv,vovv,ovv,vnvv,vonvv,onvv,nvv,vv,v

最终即为三个字符对应值相加f[o]+f[n]+f[v]=2+4+15=21

注意!!!

因为要计算sum(f),这值可能会超级大,所以要用long型!

Java

class Solution {
    public int distinctSubseqII(String s) {
        int MOD = (int)1e9+7;
        long[] f = new long[26];
        for (char cur : s.toCharArray()) {
            f[cur - 'a'] = Arrays.stream(f).sum() % MOD + 1;
        }
        return (int)(Arrays.stream(f).sum() % MOD);
    }
}

C++

class Solution {
public:
    int distinctSubseqII(string s) {
        int MOD = (int)1e9+7;
        vector<long> f(26, 0);
        for (auto cur : s) {
            f[cur - 'a'] = accumulate(f.begin(), f.end(), 1l) % MOD;
        }
        return accumulate(f.begin(), f.end(), 0l) % MOD;
    }
};

Rust

impl Solution {
    pub fn distinct_subseq_ii(s: String) -> i32 {
        let MOD = 1000000007;
        let mut f = vec![0; 26];
        for cur in s.chars() {
            f[(cur as u8 - 'a' as u8) as usize] = f.iter().sum::<i64>() % MOD + 1;
        }
        (f.iter().sum::<i64>() % MOD) as i32
    }
}

总结

完全没思路的一道题~是那种望而生畏,读完题失去梦想,看完题解觉得自己是傻子的类型……

看普通动规的题解感觉好难理解,差点放弃,然后跳到后面理清思路返回来就好理解很多,但还是只选了两种比较简洁的方式写;

以上就是Java C++题解eetcode940不同的子序列 II的详细内容,更多关于Java C++ 不同的子序列的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文