版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sengo_GWU/article/details/81852509
491. Increasing Subsequences
Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2 .
Example:
Input: [4, 6, 7, 7]
Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
套路,和以前的题目都是一个模式。一般来说回溯法速度通不过才对。
class Solution(object):
def findSubsequences(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.helper(nums, 0, [], res)
return res
def helper(self, nums, index, temp, res):
if len(temp) >= 2:
res.append(temp[:])
used = {}
for i in xrange(index, len(nums)):
# 判断递增
if len(temp) and temp[-1] > nums[i]: continue
# 判断同个位置是否用过
if nums[i] not in used:
used[nums[i]] = True
else:
continue
self.helper(nums, i+1, temp+[nums[i]], res)
46. Permutations
说什么回溯法,就是毫无智商的穷举,算什么算法?太弱智了吧
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.helper(nums, res, [])
return res
def helper(self, nums, res, cur):
if len(cur) == len(nums):
res.append(cur)
else:
for i in xrange(len(nums)):
if nums[i] not in cur:
self.helper(nums, res, cur+[nums[i]])
131. Palindrome Partitioning
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
res = []
self.helper(s, [], res)
return res
def helper(self, s, cur, res):
if not s:
res.append(cur[:])
return
for i in xrange(1, len(s) + 1):
if self.isPal(s[:i]):
self.helper(s[i:], cur + [s[:i]], res)
def isPal(self, s):
return s == s[::-1]