@@ -320,6 +320,7 @@ def letterCombinations(self, digits):
320
320
:rtype: List[str]
321
321
dfs实践
322
322
"""
323
+
323
324
def _dfs (num , string , res ):
324
325
if num == length :
325
326
res .append (string )
@@ -345,7 +346,71 @@ def fourSum(self, nums, target):
345
346
:type target: int
346
347
:rtype: List[List[int]]
347
348
"""
348
-
349
+ if len (nums ) < 3 :
350
+ return
351
+ res = []
352
+ nums = sorted (nums )
353
+ for i in range (len (nums )):
354
+ for j in range (i + 1 , len (nums )):
355
+ start = j + 1
356
+ end = len (nums ) - 1
357
+ while start < end :
358
+ if nums [i ] + nums [j ] + nums [start ] + nums [end ] == target :
359
+ if [nums [i ], nums [j ], nums [start ], nums [end ]] not in res :
360
+ res .append ([nums [i ], nums [j ], nums [start ], nums [end ]])
361
+ start += 1
362
+ end -= 1
363
+ elif nums [i ] + nums [j ] + nums [start ] + nums [end ] < target :
364
+ start += 1
365
+ else :
366
+ end -= 1
367
+
368
+ return res
369
+
370
+ # leetcode20
371
+ def isValid (self , s ):
372
+ """
373
+ :type s: str
374
+ :rtype: bool
375
+ """
376
+ data = {'(' : ')' , '[' : ']' , '{' : '}' }
377
+ keys = []
378
+ for i in range (len (s )):
379
+ if s [i ] in data .keys ():
380
+ keys .append (s [i ])
381
+ else :
382
+ try :
383
+ if s [i ] == data [keys [- 1 ]]:
384
+ keys .pop (- 1 )
385
+ else :
386
+ return False
387
+ except :
388
+ return False
389
+ if len (keys ) == 0 :
390
+ return True
391
+ else :
392
+ return False
393
+
394
+ # leetcode22
395
+ def generateParenthesis (self , n ):
396
+ """
397
+ :type n: int
398
+ :rtype: List[str]
399
+ """
400
+
401
+ def _dfs (left , right , out , res ):
402
+ if left < 0 or right < 0 or left > right :
403
+ return
404
+ if left == 0 and right == 0 :
405
+ res .append (out )
406
+ return
407
+ _dfs (left - 1 , right , out + '(' , res )
408
+ _dfs (left , right - 1 , out + ')' , res )
409
+
410
+ res = []
411
+ _dfs (n , n , '' , res )
412
+ return res
413
+
349
414
350
415
if __name__ == '__main__' :
351
- print Solution ().letterCombinations ( '123' )
416
+ print Solution ().generateParenthesis ( 3 )
0 commit comments