题目链接:93. 复原 IP 地址 - 力扣(LeetCode)
思路:跟分割字符串的题目模板一样,区别在于判断每一个数是否为0 到 255 的数,以及有没有出现前导0的情况。
class Solution(object):
def Judge255(self, s, startIndex, end):
if len(s[startIndex : end]) >= 1 and s[startIndex] == "0":
return False
return True if int(s[startIndex : end + 1]) >= 0 and int(s[startIndex : end + 1]) <= 255 else False
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
self.result = []
self.path = []
def backTracking(startIndex):
if len(self.path) > 4:
return
if len(self.path) == 4 and startIndex == len(s):
self.result.append('.'.join(self.path))
return
for i in range(startIndex, len(s)):
if self.Judge255(s, startIndex, i):
self.path.append(s[startIndex : i + 1])
backTracking(i + 1)
self.path.pop()
backTracking(0)
return self.result
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.result = []
self.path = []
self.result.append([])
def backtracking(startIndex):
if len(self.path) != 0:
self.result.append(self.path[:])
for i in range(startIndex, len(nums)):
self.path.append(nums[i])
backtracking(i + 1)
self.path.pop()
backtracking(0)
return self.result
思路:思路跟之前的去重思路一样;用used数组
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.result = []
self.path = []
self.result.append([])
self.used = [False] * len(nums)
nums.sort()
def backTracking(startIndex):
if len(self.path) != 0:
self.result.append(self.path[:])
for i in range(startIndex, len(nums)):
if i > 0 and nums[i] == nums[i - 1] and self.used[i-1] == False:#在同一层上
continue
self.used[i] = True
self.path.append(nums[i])
backTracking(i + 1)
self.path.pop()
self.used[i] = False
backTracking(0)
return self.result