The road of Leetcode Brush Problem (v) the Advanced level of--medium

Source: Internet
Author: User
Tags mul multiply strings rotate image
Problem 39. Combination Sum

  given an array with no duplicate numbers and a target, returns the combination of numbers in all arrays, with target, and each number can be reused .

* * Problem Solving ideas: **backtracking, this method can be used to solve a class of problems. Processing of attention boundary value

Class Solution (object):  
    def combinationsum (self, candidates, target): ""
        : Type Candidates:list[int]
        : Type Target:int
        : rtype:list[list[int]]
        ""
        res = []
        self.search (candidates, target, 0, [], RES) Return
        res

    def search (self, candidates, target, IDX, T_res, res):
        If target = 0:
            res.append (sorted (t_res))
            Return

        to I in range (idx, len (candidates)):
            if Target < Candidates[i]:
                continue
            t_res.append ( Candidates[i])
            self.search (candidates, target-candidates[i], I,  t_res, res)
            T_res.pop ()

Note that IDX is passed, because it can be reused, the loop inside to determine in advance whether the current target is not enough, you can reduce the required operation Problem 40. Combination Sumii

  with Problem 39, the difference is that each number can only be used once, using the same method, the transfer of IDX each time plus 1 can . Problem 43. Multiply Strings

  given two strings, each character is ' 0 '-' 9 ', solving the product of the number represented by two strings and returning .
  The solution: list The multiplication vertical, we can see corresponding to the L two string subscript is i,j number of the product, in the result position. The length is multiplied by A and b strings, resulting in the maximum res a+b, the result of the I and J multiplication, and the position of I+j and i+j+1 in the res index.

Class Solution (object):
    def multiply (self, NUM1, num2):
        res = [0] * (len (NUM1) + len (num2)) for

        I in range (len (NUM1)-1,-1,-1): For
            J in Range (Len (num2)-1,-1,-1):
                mul = Int (num1[i]) * INT (NUM2[J))
                carry = i + j
                mo D = i + j + 1
                t = mul + Res[mod]
                Res[carry] + = t//
                res[mod] = t%
        mul_res = 0 for
        i in res:
  mul_res *=
            Mul_res + = i return
        str (mul_res)
Problem 46. Permutations

  given a list (without duplicate values), find all of its possible permutations and combinations .
  Solution : with problem 39 Such problems can be solved with backtrack, in particular, in Python, if you use a list,a.append (b), all operations on B will affect the B that was added to the previous a. Therefore, to use A.append (list (b)), reapply for memory.

def search (nums, T, res):

    If Len (t) = = Len (nums):
        res.append (List (t)) #不能直接append (t), Otherwise, the contents of the Res will change with the subsequent operation of T return to 
    i in nums:
        if I in T:
            continue
        t.append (i)
        search (Nums, T, Res)
        T.pop ()


class Solution (object):  
    def permute (self, Nums): ""
        : Type Nums:list[int]
        : Rtype:list[list[int]]
        "
        res = []
        search (Nums, [], RES) return
        Res
Problem 48. Rotate Image

  given a square image, rotate clockwise 90, requiring In-place.
  The idea of solving problems: Flip the top and bottom, then transpose. If you want to rotate counterclockwise, just flip it around.

def rotate (self, matrix):
        ""
        : Type Matrix:list[list[int]]
        : rtype:void Don't return anything, modify Matri x in-place instead.
        "" " Matrix.reverse () #如果这里不能reverse, you can directly loop through
        n = len (matrix) for
        I in range (n): for
            J in range (I+1, n):
                t = ma TRIX[I][J]
                matrix[i][j] = Matrix[j][i]
                matrix[j][i] = t

Ps:python has a trick,discussion that is mentioned in the slice can be solved one step (for the non square, still valid)

def rotate (self, matrix):

        matrix[::] = Zip (*matrix[::-1])
Problem 49. Group anagrams

* * Given a list that contains STR, returns a list in which each element of the list is also a list in which all the words are composed of the same letters: for example, given ["Eat", "tea", "tan", "ate", "Nat", "Bat"], Return:
[
["ate", "eat", "tea"],
[Nat, Tan],
["Bat"]
]**。
  How to solve the problem: iterate through each str, sort first, and then use a dictionary to maintain the words with the same letter.

  def groupanagrams (self, STRs): ""
        : Type strs:list[str]
        : rtype:list[list[str] "" "
        "
        d = {}
        For i in STRs:
            s_i = str (sorted (i))
            if s_i not in D:
                d[s_i] =[i]
            else:
                d[s_i].append (i)
        Return D.values ()
Problem 54. Spiral Matrix

  given a matrix, rotate the print clockwise, from outside to inside, such as given [[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]], Output [1, 2, 3, 4, 7, 9, 8, 7].
  The idea of solving problems: given two points, upper left corner and lower right corner, then follow left-> right, Upper->, right-> left, lower->, then left upper corner move to the right, upper right corner move to the left, circulation above four printing steps, until the location point meets, notice, Because it may not be a phalanx, the last two steps of printing are to determine whether there is only one row or column, to avoid duplicate printing.

  Ideas for solving problems 2: 1. Print the first line, that is, list[0], and then remove list[0];2 from the list. Rotate the list counterclockwise 90 degrees, repeat 1,

   def spiralorder (self, Matrix): ""
        : Type Matrix:list[list[int]]
        : rtype:list[int]
        "" "Return Matrix and List (Matrix.pop (0)) + self.spiralorder (Zip (*matrix) [::-1])
Problem 55. Jump Game

  given a non-negative list, each number represents the maximum number of steps that can be jumped forward at the current position, asking if it can reach the end of the list.
  Solution: The core is to consider 0 of the situation, there are several:

     1. The length of the list is 1,return true
     2.0,return True 3 is encountered at the end of the list
     . If you encounter 0 in the middle, you should see if the maximum number of steps before 0 is greater than 2, that is, whether you can cross this 0, if not, return False. If you can just go ahead.
     4. Max_step=max (Max_step-1,nums[i] of the current position), initialized to Nums[0].
 def canjump (self, nums): If Len (nums) = = 1:return True Max_step =
                    Nums[0] for I in range (len (nums)): if nums[i] = = 0:if i = len (nums)-1:             
            Return True if Max_step <2:return False Max_step = Max (max_step-1, Nums[i]) return True 

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.