Lincode record 5 and lincode record 5

Source: Internet
Author: User

Lincode record 5 and lincode record 5
Course Schedule Frog Jump Maximum length of the receipt string Course Schedule

The course selection solution is a clear question: bfs or dfs, and then a dictionary optimization is added, I haven't figured it out for a long time. · online search algorithms · submit bfs algorithms, the use cases provided by dfs algorithms seem to be too deep in recursion. The python compiler collapsed directly. · Local debugging also collapsed ··

The core of bfs is to use an array to record the depth of each number. It is the number of courses you have to attend before this lesson, and add all those 0 to the queue, when traversing the next vertex, subtract one until the vertex is cleared. If the entry of another vertex is not 0, it cannot be completed.

I don't know what the python version is on the website. The queue is an upper-case Q, and my local python is a lower-case Q. The recurrence of dfs seems to be passable.

class Solution:    # @param {int} numCourses a total of n courses    # @param {int[][]} prerequisites a list of prerequisite pairs    # @return {boolean} true if can finish all courses or false    def canFinish(self, numCourses, prerequisites):        import Queue        import sys        sys.setrecursionlimit(1000000)        if len(prerequisites)<2:return True        dicp={}        inlist=[0]*numCourses        for p in prerequisites:            dicp.setdefault(p[1],[])            dicp[p[1]].append(p[0])            inlist[p[0]] += 1        q=Queue.Queue()        for i in range(numCourses):            if inlist[i] == 0:q.put(i)                while not q.empty():            cur=q.get()            if cur not in dicp:continue            for i in dicp[cur]:                inlist[i] -=1                if inlist[i]==0:q.put(i)                for i in inlist:            if i !=0 :return False        return True          ''' DFS          visit=[0]*numCourses        def canfinishdfs(visit,i):            if visit[i]==-1:return False            if visit[i]==1:return True            visit[i]=-1            if i in dicp:                for cur in dicp[i]:                    if not canfinishdfs(visit,cur):return False            visit[i]=1            return True                    for i in range(numCourses):             if not canfinishdfs(visit,i):                 return False                return True        '''        

Arrange the course, just like above. Add an array to output. Finally, you can select an output class, not an empty array.

class Solution:    # @param {int} numCourses a total of n courses    # @param {int[][]} prerequisites a list of prerequisite pairs    # @return {int[]} the course order    def findOrder(self, numCourses, prerequisites):        # Write your code here        import Queue        dicp={}        inlist=[0]*numCourses        for p in prerequisites:            dicp.setdefault(p[1],[])            dicp[p[1]].append(p[0])            inlist[p[0]] += 1        q=Queue.Queue()        res=[]        for i in range(numCourses):            if inlist[i] == 0:                q.put(i)                res.append(i)                while not q.empty():            cur=q.get()            if cur not in dicp:continue            for i in dicp[cur]:                inlist[i] -=1                if inlist[i]==0:                    q.put(i)                    res.append(i)                                for i in inlist:            if i !=0 :                return []        return res

Frog Jump

For the frog jumping Problem, traverse from the back to the front and calculate whether the number can reach this point from the last 3rd. the DFS algorithm is the first recursive loop ··, the key lies in the failed cache node,

if len(stones)==1:return True        # memo=set()        # target=stones[-1]        # stones=set(stones)                # def bt(cur,k):        #     if (cur,k) in memo:        #         return False        #     if cur==target:        #         return True        #     if cur>target or cur<0 or k<=0 or cur not in stones:        #         return False        #     dirs=[k-1,k,k+1]        #     for c in dirs:        #         if (cur+c)in stones:        #             if bt(cur+c,c):        #                 return True        #     memo.add((cur,k))        #     return False        # return bt(0,0)                stone_set, fail = set(stones), set()        stack = [(0, 0)]        while stack:            stone, jump = stack.pop()            for j in (jump-1, jump, jump+1):                s = stone + j                if j > 0 and s in stone_set and (s, j) not in fail:                    if s == stones[-1]:                        return True                    stack.append((s, j))            fail.add((stone, jump))        return False

Maximum length of the retrieval string-just group traversal:

class Solution:    # @param {string} s a string which consists of lowercase or uppercase letters    # @return {int} the length of the longest palindromes that can be built    def longestPalindrome(self, s):        # Write your code here        dics={}        for i in s:            dics.setdefault(i,[])            dics[i].append(i)        sum=0        flag=False        for di in dics:            n=len(dics[di])            if n>1:                if n%2 !=0:                    sum+=n-1                    flag=True                else:                    sum+=n            else:                flag=True        if flag:sum+=1        return sum

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.