String - 91. 93. 151. 165. Dynamic Programming - 70. 95. 96. 139. 198.

91. Decode Ways

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

提示:斐波那契变形。从后往前遍历,如果当前元素与前一个元素组合小于27,res = count + preCount,否则res不变。

     解释一下,加如当前res = 3,在字符串前面加上一个数,如果其能够与后面的数结合成字母,那么为答案添加了preCount种可能,否则res不变。

答案:

class Solution {
public:
    int numDecodings(string s) {
        if(s.length() == 0) return 0;
        int pre = 27, digit = 0, ret = 0, count = 1, preCount = 1;
        for(int i = s.length()-1; i >= 0; i--){
            digit = s[i] - '0';
            if(digit == 0) ret = 0;
            else ret = count + (digit*10 + pre < 27 ? preCount : 0);
            preCount = count; count = ret; pre = digit;
        }
        return ret;
    }
};

93Restore IP Addresses


Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

提示:straightforward

答案:

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> ret;
        string ans;
        for (int a=1; a<=3; a++)
        for (int b=1; b<=3; b++)
        for (int c=1; c<=3; c++)
        for (int d=1; d<=3; d++)
            if (a+b+c+d == s.length()) {
                int A = stoi(s.substr(0, a));
                int B = stoi(s.substr(a, b));
                int C = stoi(s.substr(a+b, c));
                int D = stoi(s.substr(a+b+c, d));
                if (A<=255 && B<=255 && C<=255 && D<=255)
                    if ( (ans=to_string(A)+"."+to_string(B)+"."+to_string(C)+"."+to_string(D)).length() == s.length()+3)
                        ret.push_back(ans);
            }    
        return ret;
    }
};

151Reverse Words in a String

Given an input string, reverse the string word by word.

Example:  

Input: "the sky is blue",
Output: "blue is sky the".

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve it in-place in O(1) space.

提示:首先把s反转,然后将每一个单词反转

答案:

class Solution {
public:
   void reverseWords(string &s) {
        reverse(s.begin(), s.end());
        int storeIndex = 0;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] != ' ') {
                if (storeIndex != 0) s[storeIndex++] = ' ';
                int j = i;
                while (j < s.size() && s[j] != ' ') { s[storeIndex++] = s[j++]; }
                reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);
                i = j;
            }
        }
        s.erase(s.begin() + storeIndex, s.end());
    }
};

165Compare Version Numbers

Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Example 1:

Input: version1 = "0.1", version2 = "1.1"
Output: -1

Example 2:

Input: version1 = "1.0.1", version2 = "1"
Output: 1

Example 3:

Input: version1 = "7.5.2.4", version2 = "7.5.3"
Output: -1

70Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

提示:斐波那契数列。例如:要想到达第5台阶,那么其前一步是到达第4台阶或者第3台阶,把到达两者的路径数相加即可。

为了减少代码行,算式a+b,其中的b变为了下一次计算的a,a+b变为了下一次计算的b。

答案:

class Solution {
public:
    int climbStairs(int n) {
        int a = 1, b = 1;
        while (n--)
            a = (b += a) - a;
        return a;
    }
};

95Unique Binary Search Trees II

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

提示:从1到n作为根节点遍历,定义左右子树,递归

答案:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<TreeNode *> generate(int beg, int end)
    {
        vector<TreeNode* > ret;
        if (beg > end)
        {
            ret.push_back(NULL);
            return ret;
        }
        
        for(int i = beg; i <= end; i++)
        {
            vector<TreeNode* > leftTree = generate(beg, i - 1);
            vector<TreeNode* > rightTree = generate(i + 1, end);
            for(int j = 0; j < leftTree.size(); j++)
                for(int k = 0; k < rightTree.size(); k++)
                {
                    TreeNode *node = new TreeNode(i + 1);
                    ret.push_back(node);
                    node->left = leftTree[j];
                    node->right = rightTree[k];              
                }           
        }
        
        return ret;
    }
    vector<TreeNode *> generateTrees(int n) {
        if (n == 0) {
            vector<TreeNode *> ret;
            return ret;
        }
        return generate(0,n-1);
    }
};

96Unique Binary Search Trees


Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

提示:  number of unique trees: G(n) = F(1, n) + F(2, n) + ... + F(n, n).
            F(i, n) = G(i-1) * G(n-i) 1 <= i <= n 

            G(n) = G(0) * G(n-1) + G(1) * G(n-2) + … + G(n-1) * G(0)

       要求G(n)就要求G(0)...G(n-1),所以用i遍历1到n,j遍历1到i。

答案:

class Solution {
public:
    int numTrees(int n) {
        vector<int> r(n+1);
        r[0] = 1;
        r[1] = 1;
        
        for (int i = 2; i <= n; ++i) {
            for (int j = 1; j <= i; ++j) {
                r[i] += r[j-1]*r[i-j]; 
            }    
        }
        return r[n];
    }
};

139Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

提示:i从1到s.size(),检查以i-1为结尾长为i-j的字符串是否在字典里,前提是j必须为0或者为上一个单词的断点。

答案:

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

198House Robber


You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

提示:用i遍历,当前结点的最大值=max(前前结点的最大值+nums[i], 前结点的最大值)

答案:

class Solution {
public:
    int rob(vector<int>& nums) { 
        int n = nums.size(), prePreMax = 0, preMax= 0;
        for (int i = 0; i < n; i++) {
            int curMax = max(prePreMax + nums[i], preMax);
            prePreMax = preMax;
            preMax= curMax;
        }
        return preMax;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值