LeetCode 2016 385,365,211,115

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 istringstream
		int 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 ends
		return 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 x
		and y such that ax+by=d
		In addition, the greatest common divisor d is the smallest positive integer that can be written as ax + by
		every 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) = 2
	8 is multiple of 2
	so this input is valid and we have:
		-1 * 4 + 6 * 2 = 8
In 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个队列,一个放前一个点的所有情况;一个放生成的新的点的所有情况。
// Code
class 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];
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值