Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2311. Longest Binary Subsequence Less Than or Equal to K #129

Open
Woodyiiiiiii opened this issue Jun 20, 2022 · 0 comments
Open

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Jun 20, 2022

很明显要用到DP。而且题目提到subsequence,这种题型解题思路大概是遍历每个字符,然后从后往前遍历DP。

问题是,如何定义DP的状态。DP的长度肯定是字符串的长度,k的长度太大了肯定不是。

这里定义DP状态:dp[i]表示长度为i的最小之和

class Solution {
    
    public int longestSubsequence(String s, int k) {

        int dp[] = new int[s.length() + 1];
        int res = 0;
        
        for (char c : s.toCharArray()) {
            
            if (dp[res] * 2 + c - '0' <= k) {
                dp[res + 1] = dp[res] * 2 + c - '0';
                res++;
            }
            
            for (int i = res; i > 0; --i) {
                dp[i] = Math.min(dp[i], dp[i - 1] * 2 + c - '0');    
            }
            
        }
        
        return res;

    }
    
}

另一种做法是贪心法,但不赘述,详情看引用2。

时隔一年重新做了这道题,发现这题就类似于基础题LIS

当然在这里不像No.300,是不能用二分来优化了。


Reference:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant