LeetCode 2016 385,365,211,115

来源:互联网 发布:思科log 端口 编辑:程序博客网 时间:2024/05/16 11:00

385 Mini Parser

// -------------------- Seeing Discuss -----------// I really have no idea about this kind of problem// I just retyped the codes from discuss// url://https://discuss.leetcode.com/topic/54258/python-c-solutions/2// Things learned:// 1. 一串字符串,提取出数字,可以直接用istringstream// 2. 题中注释写的函数,记得直接用。// Codes:/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { *   public: *     // Constructor initializes an empty nested list. *     NestedInteger(); * *     // Constructor initializes a single integer. *     NestedInteger(int value); * *     // Return true if this NestedInteger holds a single integer, rather than a nested list. *     bool isInteger() const; * *     // Return the single integer that this NestedInteger holds, if it holds a single integer *     // The result is undefined if this NestedInteger holds a nested list *     int getInteger() const; * *     // Set this NestedInteger to hold a single integer. *     void setInteger(int value); * *     // Set this NestedInteger to hold a nested list and adds a nested integer to it. *     void add(const NestedInteger &ni); * *     // Return the nested list that this NestedInteger holds, if it holds a nested list *     // The result is undefined if this NestedInteger holds a single integer *     const vector<NestedInteger> &getList() const; * }; */class Solution {public:    NestedInteger deserialize(string s) {        istringstream in(s);return deserialize(in);}private:NestedInteger deserialize(istringstream &in){// 1 istringstreamint number;if(in >> number)return NestedInteger(number);in.clear();in.get();NestedInteger list;while(in.peek()!=']'){list.add(deserialize(in));if(in.peek()==',') in.get();}in.get();// 1 istringstream endsreturn list;}};


365 Water and Jug Problem

// ----------------Seeing Discuss-----------// 数学方面的东东,我果然不行。。。囧。。。。// Discuss里面把这个问题转换成了gcd问题,也就是求x和y的最大公约数,看是不是z的约数。// 找到a和b使得,ax+by=z, 当a,b大于0时,相当于往里面倒水;当a,b小于零时,相当于往外倒水。// url://https://discuss.leetcode.com/topic/49238/math-solution-java-solution/*This is a pure Math problem. We need the knowledge of number theory to cover the proof and solution. No idea why microsoft uses this problem in real interview.The basic idea is to use the property of Bézout's identity and check if z is a multiple of GCD(x, y)Quote from wiki:Bézout's identity (also called Bézout's lemma) is a theorem in the elementary theory of numbers:let a and b be nonzero integers and let d be their greatest common divisor. Then there exist integers xand y such that ax+by=dIn addition, the greatest common divisor d is the smallest positive integer that can be written as ax + byevery integer of the form ax + by is a multiple of the greatest common divisor d.If a or b is negative this means we are emptying a jug of x or y gallons respectively.Similarly if a or b is positive this means we are filling a jug of x or y gallons respectively.x = 4, y = 6, z = 8.GCD(4, 6) = 28 is multiple of 2so this input is valid and we have:-1 * 4 + 6 * 2 = 8In this case, there is a solution obtained by filling the 6 gallon jug twice and emptying the 4 gallon jug once. (Solution. Fill the 6 gallon jug and empty 4 gallons to the 4 gallon jug. Empty the 4 gallon jug. Now empty the remaining two gallons from the 6 gallon jug to the 4 gallon jug. Next refill the 6 gallon jug. This gives 8 gallons in the end)*//* 学到的东西1. 学会转化,问题可能就是你会的2. gcd的写法*/// Code:class Solution {public:    bool canMeasureWater(int x, int y, int z)     {        // limit brought by the statement that water is finally in one or two jugs        if(x+y<z) return false;                // case x or y is zero        if(x==z || y==z ||x+y==z) return true;                // get GCD        return z%GCD(x,y) ==0;    }private:    int GCD(int a,int b)    {                while(b!=0)        {            int tmp = b;            b=a%b;            a=tmp;        }        return a;    }};// ----------WA 1ST----------// 把题目转换成01背包,可以出现的容量当做物品// 21 / 33 test cases passed.// WA data point:// Input://13//11//1//Output://false//Expected://true// Code/*class Solution {public:    bool canMeasureWater(int x, int y, int z)    {        if(z==0) return true;        vector<int> coins;        coins.clear();        int minVal = min(x,y),maxVal = max(x,y);        if (x!=0) coins.push_back(x);        if (y!=0) coins.push_back(y);        if (maxVal-minVal != 0) coins.push_back(maxVal-minVal);        int tmp = 0;        while(minVal!=0 && tmp<maxVal) tmp+=minVal;        tmp = tmp - maxVal;        if(tmp>0) coins.push_back(tmp);        bool flag = false;        for(int i=0;i<coins.size();i++)        {            if (coins[i]<=z) flag =true;        }        if (!flag) return false;        int ans = coinChange(coins,z);        if (ans==-1) return false;        else return true;    }private:    static bool cmp(int x,int y)    {        return x>y;    }    int coinChange(vector<int>& coins, int amount)    {        if(amount == 0) return 0;        int lcoins = coins.size();        sort(coins.begin(),coins.end(),cmp);        vector<long long> f(amount+10,INT_MAX);        for(int i=0;i<lcoins;i++)        {            if (coins[i]<=amount)                f[coins[i]]=1;        }        for(int i=0;i<lcoins;i++)        {            for(int j=amount;j>=0;j--)            {                if (j-coins[i]>0)                {                    f[j]=min(f[j-coins[i]]+1,f[j]);                }            }        }        if (f[amount]==INT_MAX) return -1;        else return f[amount];    }};*/

211 Add and Search Word - Data structure design

// 依次遍历要查找的单词的每一位字母//1. 特定字母直接搜索//2. . 遍历a-z,看哪个存在。//3. 维护2个队列,一个放前一个点的所有情况;一个放生成的新的点的所有情况。// Codeclass TrieNode{public:    // Initialize your data structure here.    TrieNode* child[27];    bool word;    TrieNode()    {        word=false;        for(int i=1;i<=26;i++) child[i]=NULL;    }};class WordDictionary{public:    WordDictionary()    {        root = new TrieNode();    }    // Adds a word into the data structure.    void addWord(string word)    {        TrieNode* tmproot=root;        for(int i=0;i<word.size();i++)        {            int ch=word[i]-'a'+1;            if (tmproot->child[ch]!=NULL)            {                tmproot=tmproot->child[ch];                continue;            }            else            {                TrieNode* tmpnode = new TrieNode();                tmproot->child[ch]= tmpnode;                tmproot=tmpnode;            }        }        tmproot->word=true;    }    // Returns if the word is in the data structure. A word could    // contain the dot character '.' to represent any one letter.    bool search(string word)    {        TrieNode* tmproot;        vector<queue<TrieNode*> >q;        q.resize(2);        while(!q[0].empty()) q[0].pop();        while(!q[1].empty()) q[1].pop();        int now = 0;        q[0].push(root);        bool flagWord;        for(int i=0;i<word.size();i++)        {            flagWord = false;            while(!q[now].empty())            {                tmproot = q[now].front();q[now].pop();                if (word[i]=='.')                {                    for(int ch = 1;ch<=26;ch++)                    {                        if (tmproot->child[ch]!=NULL)                        {                            q[1-now].push(tmproot->child[ch]);                            if (tmproot->child[ch]->word) flagWord = true;                        }                    }                }                else                {                    int ch=word[i]-'a'+1;                    if (tmproot->child[ch]!=NULL)                    {                        q[1-now].push(tmproot->child[ch]);                        if (tmproot->child[ch]->word) flagWord = true;                    }                }            }            if (q[1-now].empty()) return false;            now = 1-now;        }        return flagWord;    }private:    TrieNode* root;};

115 Distinct Subsequences

class Solution {public:    int numDistinct(string s, string t)    {        int m=t.size(), n = s.size();        vector<vector<int> > f(m+1,vector<int> (n+1,0));        for(int i=0;i<=n;i++) f[0][i]=1;        for(int j=1;j<=n;j++)            for(int i=1;i<=m;i++)                f[i][j]=f[i][j-1]+(t[i-1]==s[j-1]?f[i-1][j-1]:0);        return f[m][n];    }};




0 0
原创粉丝点击