【2019-06-16】leetcode(50-60)

50隙笆、Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/2^2 = 1/4 = 0.25
分析

"""
計算pow(x,n)
"""

class Solution:
    # @param x, a float
    # @param n, a integer
    # @return a float
    def myPow(self, x, n):
        if n == 0:
            return 1.0
        elif n < 0:
            return 1 / self.myPow(x, -n)
        elif n % 2:
            return self.myPow(x*x,n//2)*x
        else:
            return self.myPow(x*x,n//2)

51撑柔、N-Queens
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

class Solution:
    # @return a list of lists of string
    def solveNQueens(self, n):
        def check(k, j):  # check if the kth queen can be put in column j!
            for i in range(k):
                if board[i]==j or abs(k-i)==abs(board[i]-j):
                    return False
            return True
        def dfs(depth, valuelist):
            if depth==n: res.append(valuelist); return
            for i in range(n):
                if check(depth,i): 
                    board[depth]=i
                    s='.'*n
                    dfs(depth+1, valuelist+[s[:i]+'Q'+s[i+1:]])
        board=[-1 for i in range(n)]
        res=[]
        dfs(0,[])
        return res

52铅忿、N-Queens II
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.

"""
N 皇后問題2
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
"""
class Solution:
    # @return an integer
    def totalNQueens(self, n):
        def check(k, j):  # check if the kth queen can be put in column j!
            for i in range(k):
                if board[i]==j or abs(k-i)==abs(board[i]-j):
                    return False
            return True
        board=[-1 for i in range(n)]
        row=0; col=0; sum=0
        while row<n:
            while col<n:
                if check(row, col):
                    board[row]=col
                    col=0
                    break
                else:
                    col+=1
            if board[row]==-1:             #如果為真檀训,即為在這一行找不到位置放置皇后
                if row==0:                 #如果在第0行也找不到位置放置皇后了,說明所有的情況已經(jīng)迭代完畢了渗鬼,執(zhí)行break跳出操作荧琼。
                    break
                else:
                    row-=1                                            #這條語句用來回溯到上一行
                    col=board[row]+1                      #回溯到上一行時,皇后放置的位置要加1堰乔,也就是開始試驗下一列
                    board[row]=-1                      #然后將這一行的值重置為-1镐侯,也就是說要重新尋找皇后的位置了
                    continue
            if row==n-1:                      #當row==n-1時被盈,說明最后一行的皇后位置也確定了,得到了一個解
                sum+=1
                col=board[row]+1
                board[row]=-1
                continue
            row+=1
        return sum

53袜瞬、Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
分析
Maximum Subarray
和最大的子串
基本思路是這樣的邓尤,在每一步贴谎,我們維護兩個變量,一個是全局最優(yōu)澈魄,就是到當前元素為止最優(yōu)的解是仲翎,一個是局部最優(yōu)铛漓,就是必須包含當前元素的最優(yōu)的解浓恶。
動態(tài)規(guī)劃的遞推式(這是動態(tài)規(guī)劃最重要的步驟结笨,遞歸式出來了,基本上代碼框架也就出來了)伐憾。
假設我們已知第i步的global[i](全局最優(yōu))和local[i](局部最優(yōu))赫模,那么第i+1步的表達式是:
local[i+1]=Math.max(A[i], local[i]+A[i]),
就是局部最優(yōu)是一定要包含當前元素扫外,所以不然就是上一步的局部最優(yōu)local[i]+當前元素A[i](因為local[i]一定包含第i個元素廓脆,所以不違反條件),
但是如果local[i]是負的驾讲,那么加上他就不如不需要的吮铭,所以不然就是直接用A[i]颅停;
global[i+1]=Math(local[i+1],global[i]),
有了當前一步的局部最優(yōu)纸肉,那么全局最優(yōu)就是當前的局部最優(yōu)或者還是原來的全局最優(yōu)
(所有情況都會被涵蓋進來喊熟,因為最優(yōu)的解如果不包含當前元素,那么前面會被維護在全局最優(yōu)里面烦味,如果包含當前元素壁拉,那么就是這個局部最優(yōu))岩遗。

class Solution:
    # @param A, a list of integers
    # @return an integer
    def maxSubArray(self, A):
        ThisSum = 0
        MaxSum = -10000
        
        for i in range( 0, len(A) ):
            if ThisSum < 0:
                ThisSum = 0
            ThisSum = ThisSum + A[ i ]
            MaxSum = max( ThisSum, MaxSum )

        return MaxSum

54、Spiral Matrix螺旋矩陣
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
分析

#回字形輸出矩陣
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        m=len(matrix)#行
        n=len(matrix[0])#列
        if m==0:
            return []
        r,l=0,0 
        m-=1
        n-=1
        ans=[]
        while r<=n and l<=m:
            for i in range(r,n+1):
                ans.append(matrix[l][i])
            l+=1
            if l>m:
                break
            for i in range(l,m+1):
                ans.append(matrix[i][n])
            n-=1
            i=n
            if n<r:
                break
            while i>=r:
                ans.append(matrix[m][i])
                i-=1
            m-=1
            i=m
            if m<1:
                break
            while i>=l:
                ans.append(matrix[i][r])
                i-=1
            r+=1
        return ans
        

55蔬芥、Jump Game跳躍游戲
Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.

分析:
Jump Game
給定一個非負整數(shù)數(shù)組笔诵,最初定位在數(shù)組的第一個索引處姑子。
數(shù)組中的每個元素表示該位置的最大跳轉(zhuǎn)長度。
確定您是否能夠到達最后一個索引谢翎。

[3,2,2,0,4]
b=3
a=5
(1)i=1, b=2,b=max(2,nums[1])=max(2,2)=2 3,2,2
(2)i=2, b=1,b=max(2,nums[2])=max(1,2)=2 3,2,2,0,4 //結束

[3,5,1,0,4]
b=3
a=5
(1)i=1, b=2,b=max(2,nums[1])=max(2,5)=5. 3,5,1,0,4 //結束

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        a=len(nums)
        b=nums[0]
        for i in range(1,a):
            if b>0:
                b-=1
                b=max(b,nums[i])
            else:
                return False
        return True

56森逮、Merge Intervals區(qū)間合并
Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals.sort(key=lambda x : x[0]) #按照每個list的第一個數(shù)字排序
        ans,size = [],len(intervals)
        if size==0:
            return ans
        tmp=intervals[0]
        for i in intervals:
            if i[0]<=tmp[1]:
                tmp[1]=max(i[1],tmp[1])
            else:
                ans.append(tmp)
                tmp=i
        ans.append(tmp)
        return ans 

57磁携、 Insert Interval區(qū)間插入
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

分析:
插入?yún)^(qū)間
一組非負數(shù)據(jù)區(qū)間谊迄,插入一個新的區(qū)間,如果可以歪脏,合并
ex.intervals=[[1,3],[6,9]], newInterval=[2,5] =====[[1,5],[6,9]]
intervals=[[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]===== [[1,2],[3,10],[12,16]]
思路:將新的區(qū)間插入到list中粮呢,數(shù)組排序合并

class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        intervals.append(newInterval)
        intervals.sort(key=lambda x:x[0])
        length=len(intervals)
        res=[]
        for i in range(length):
            if res==[]:
                res.append(intervals[i])
            else:
                size=len(res)
                if res[size-1][0]<=intervals[i][0]<=res[size-1][1]:
                    res[size-1][1]=max(intervals[i][1],res[size-1][1])
                else:
                    res.append(intervals[i])
        return res

58、 Length of Last Word最后一個字符的長度
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"
Output: 5
分析:

最后一個單詞的長度
思路:splitt

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.split()[len(s.split())-1]) if s.split()!=[] else 0

59移怯、Spiral Matrix II螺旋矩陣
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
分析:

螺旋矩陣
給定一個正數(shù)n舟误,生成一個方陣姻乓,填充的元素為1到n^2

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        A=[]
        x=n*n+1
        while x>1:
            x,y=x-len(A),x
            A=[list(range(x,y))]+list(zip(*A[::-1]))
        return A

60眯牧、Permutation Sequence全排列取指定的返回值

The set [1,2,3,...,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

"123"

"132"

"213"

"231"

"312"

"321"

Given n and k, return the kth permutation sequence.

分析:

序列全排列

按照順序排列学少,返回第k個序列

n=3,k=3

123

132

213 ====k

231

312

321

n個正數(shù)秧骑,每個數(shù)在最高位出現(xiàn)(n-1)!次,最高位確定后绒疗,在第二高位出現(xiàn)(n-2)!次骂澄,最高位和次高位確定后,在第三高位出現(xiàn)次數(shù)(n-3)!次磨镶。健提。。矩桂。。依次類推雹锣,數(shù)字不會超過9癞蚕。

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        res=''
        k-=1
        fac=1
        for i in range(1,n):
            fac*=i
            num=[1,2,3,4,5,6,7,8,9]
        for i in reversed(range(n)):
            curr=num[int(k//fac)]
            res+=str(curr)
            num.remove(curr)
            if i!=0:
                k%=fac
                fac/=i
        return res
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末桦山,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子会放,更是在濱河造成了極大的恐慌,老刑警劉巖咧最,帶你破解...
    沈念sama閱讀 219,427評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件矢沿,死亡現(xiàn)場離奇詭異,居然都是意外死亡瑟匆,警方通過查閱死者的電腦和手機栽惶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人宪迟,你說我怎么就攤上這事〈┮牵” “怎么了意荤?”我有些...
    開封第一講書人閱讀 165,747評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長紫谷。 經(jīng)常有香客問我捐寥,道長,這世上最難降的妖魔是什么握恳? 我笑而不...
    開封第一講書人閱讀 58,939評論 1 295
  • 正文 為了忘掉前任乡洼,我火速辦了婚禮,結果婚禮上拔稳,老公的妹妹穿的比我還像新娘锹雏。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 67,955評論 6 392
  • 文/花漫 我一把揭開白布腰耙。 她就那樣靜靜地躺著挺庞,像睡著了一般。 火紅的嫁衣襯著肌膚如雪选侨。 梳的紋絲不亂的頭發(fā)上然走,一...
    開封第一講書人閱讀 51,737評論 1 305
  • 那天,我揣著相機與錄音晨仑,去河邊找鬼。 笑死洪己,一個胖子當著我的面吹牛竟贯,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播拱镐,決...
    沈念sama閱讀 40,448評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼持际,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了选酗?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,352評論 0 276
  • 序言:老撾萬榮一對情侶失蹤呜叫,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后朱庆,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體闷祥,經(jīng)...
    沈念sama閱讀 45,834評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,992評論 3 338
  • 正文 我和宋清朗相戀三年箱硕,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片栓拜。...
    茶點故事閱讀 40,133評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡惠昔,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出镇防,到底是詐尸還是另有隱情,我是刑警寧澤诫给,帶...
    沈念sama閱讀 35,815評論 5 346
  • 正文 年R本政府宣布饲漾,位于F島的核電站缕溉,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏证鸥。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,477評論 3 331
  • 文/蒙蒙 一泉褐、第九天 我趴在偏房一處隱蔽的房頂上張望鸟蜡。 院中可真熱鬧,春花似錦揉忘、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽狂丝。三九已至,卻和暖如春倍试,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背易猫。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評論 1 272
  • 我被黑心中介騙來泰國打工具壮, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人攘已。 一個月前我還...
    沈念sama閱讀 48,398評論 3 373
  • 正文 我出身青樓怜跑,卻偏偏與公主長得像,于是被迫代替她去往敵國和親峡眶。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,077評論 2 355

推薦閱讀更多精彩內(nèi)容