Leetcode 139. Word Split & Leetcode 55. Jumping Game [Research in reverse order]

Leetcode 139. Word splitting

Problem Description

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine whether s can be split into one or more words that appear in the dictionary by spaces.

Description:

  • You can reuse the words in the dictionary when splitting.
  • You can assume that there are no duplicate words in the dictionary.

Input: s = "leetcode", wordDict = ["leet", "code"]
Output:true

Problem solving report

dp[i]Indicates whether sthe 0first character to the ifirst character in the string can be split.

To determine dp[i]whether it can be split, from i-1to 0reverse search, whether there is one dp[j], which can be split and the jcharacter icomposed of the first character to the first character can be found in the dictionary.

Implementation code

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int n=s.size();
        set<string>setWords;
        for(int i=0;i<wordDict.size();i++){
            setWords.insert(wordDict[i]);
        }
        vector<int>dp(n+1,0);
        dp[0]=1;
        for(int i=1;i<=n;i++){
            for(int j=i-1;j>=0;j--){
                if(dp[j]&&setWords.find(s.substr(j,i-j))!=setWords.end()){
                    dp[i]=1;
                    break;
                }
            }
        }
        return dp[n];
    }
};

References

[1] Leetcode jumping game
[2] Problem area bonheur

Leetcode 55. Jumping game

Problem Description

Given an array of non-negative integers, you are initially in the first position of the array.

Each element in the array represents the maximum length you can jump at that position.

Determine if you can reach the last position.

Problem solving report

dp[i]Indicates iwhether the first position is reachable.

When it is determined dp[i]whether reachable from i-1the 0reverse search, if there is one dp[j], and up to itsj+num[j]>=i

Implementation code

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int n=nums.size();
        if(n==1){
            return 1;
        }
        vector<int>dp(n,0);
        dp[0]=1;
        for(int i=0;i<n;i++){
            for(int j=i-1;j>=0;j--){
                if(dp[j]&&j+nums[j]>=i){
                    dp[i]=1;
                    break;
                }
            }
        }
        return dp[n-1];
    }
};

References

[1] Leetcode 55. Jumping game

MD_
Published 139 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_27690765/article/details/105347058