leetcode 回溯法解题
Posted yutingting
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 回溯法解题相关的知识,希望对你有一定的参考价值。
leetcode 17.电话号码的字母组合
class Solution(object):
def letterCombinations(self, digits):
if not digits: return []
res = []
d = [‘‘, ‘*‘, ‘abc‘, ‘def‘, ‘ghi‘, ‘jkl‘, ‘mno‘, ‘pqrs‘, ‘tuv‘, ‘wxyz‘]
def dfs(tmp, index):
if index == len(digits):
res.append(tmp)
return
c = digits[index]
letters = d[ord(c)-48]
for i in letters:
dfs(tmp+i, index+1)
dfs(‘‘, 0)
return res
# 求解
s = Solution()
s.letterCombinations(‘23‘)
# return
[‘ad‘, ‘ae‘, ‘af‘, ‘bd‘, ‘be‘, ‘bf‘, ‘cd‘, ‘ce‘, ‘cf‘]
leetcode 22.括号生成
class Solution(object):
def generateParenthesis(self, n):
if not n: return []
res = []
self.dfs(res, n, n, ‘‘)
return res
def dfs(self, res, left, right, path):
if left==0 and right==0:
res.append(path)
return
if left>0:
self.dfs(res, left-1, right, path+‘(‘)
if left<right:
self.dfs(res, left, right-1, path+‘)‘)
leetcode 39.组合总和
class Solution(object):
def combinationSum(self, candidates, target):
def backtrack(i, tmp_sum, tmp):
if tmp_sum>target and i==n: return
if tmp_sum==target:
res.append(tmp)
return
for j in range(i, n):
if tmp_sum + candidates[j] > target: break
backtrack(j, tmp_sum+candidates[j], tmp+[candidates[j]])
candidates.sort()
n = len(candidates)
res = []
backtrack(0, 0, [])
return res
leetcode 40.组合总和 II
class Solution(object):
def combinationSum2(self, candidates, target):
def backtrack(i, tmp_sum, tmp):
if tmp_sum>target and i==n: return
if tmp_sum==target:
res.append(tmp)
return
for j in range(i, n):
if tmp_sum+candidates[j]>target: break
if j>i and candidates[j]==candidates[j-1]: continue
backtrack(j+1, tmp_sum+candidates[j], tmp+[candidates[j]])
candidates.sort()
n = len(candidates)
res = []
backtrack(0, 0, [])
return res
leetcode 46.全排列
class Solution(object):
def permute(self, nums):
def backtrack(nums, tmp):
if not nums:
res.append(tmp)
return
for i in range(len(nums)):
backtrack(nums[:i]+nums[i+1:], tmp+[nums[i]])
res = []
backtrack(nums, [])
return res
leetcode 47.全排列 II
class Solution(object):
def permuteUnique(self, nums):
def backtrack(nums, tmp):
if not nums:
res.append(tmp)
return
for i in range(len(nums)):
if i>0 and nums[i]==nums[i-1]: continue
backtrack(nums[:i]+nums[i+1:], tmp+[nums[i]])
nums.sort()
res = []
backtrack(nums, [])
return res
leetcode 51.N皇后
class Solution(object):
def solveNQueens(self, n):
# 记录 行, 列, 正对角,负对角,不能有两个以上的棋子.
# 正对角就是相加之和一样的
# 负对角就是相减z之差一样的
def backtrack(i, tmp, col, z_dig, f_dig):
if i==n:
res.append(tmp)
return
for j in range(n):
if j not in col and i+j not in z_dig and i-j not in f_dig:
backtrack(i+1, tmp+[s[:j]+‘Q‘+s[j+1:]], col | {j}, z_dig | {i+j}, f_dig | {i-j})
res = []
s = ‘.‘*n
backtrack(0, [], set(), set(), set())
return res
leetcode 52.N皇后 II
class Solution(object):
def totalNQueens(self, n):
# 思路与上题类似
def backtrack(i, col, z_dig, f_dig):
if i==n: return True
for j in range(n):
if j not in col and i+j not in z_dig and i-j not in f_dig:
if backtrack(i+1, col|{j}, z_dig|{i+j}, f_dig|{i-j}): self.res += 1
return False
self.res = 0
backtrack(0, set(), set(), set())
return self.res
leetcode 77.组合
class Solution(object):
def combine(self, n, k):
def backtrack(nums, tmp):
if len(tmp)==k:
res.append(tmp)
return
for i in range(len(nums)):
backtrack(nums[i+1:], tmp+[nums[i]])
res = []
nums = range(1, n+1)
backtrack(nums, [])
return res
leetcode 78.子集
class Solution(object):
def subsets(self, nums):
def backtrack(nums, tmp):
res.append(tmp)
for i in range(len(nums)):
backtrack(nums[i+1:], tmp+[nums[i]])
res = []
backtrack(nums, [])
return res
leetcode 90.子集 II
class Solution(object):
def subsetsWithDup(self, nums):
def backtrack(nums, tmp):
res.append(tmp)
for i in range(len(nums)):
if i>0 and nums[i]==nums[i-1]: continue
backtrack(nums[i+1:], tmp+[nums[i]])
res = []
nums.sort()
backtrack(nums, [])
return res
leetcode 131.分割回文串
class Solution(object):
def partition(self, s):
def helper(s, tmp):
if not s:
res.append(tmp)
return
for i in range(1, len(s)+1):
if s[:i]==s[:i][::-1]:
helper(s[i:], tmp+[s[:i]])
res = []
helper(s, [])
return res
leetcode 132.分割回文串 II
class Solution(object):
def minCut(self, s):
if s==s[::-1]: return 0
res = float("inf")
for i in range(1, len(s)+1):
if s[:i]==s[:i][::-1]:
res = min(self.minCut(s[i:])+1, res)
return res
以上是关于leetcode 回溯法解题的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode] Backtracking回溯法解题思路
leetcode算法题基础(四十五) 回溯算法总结 回溯法的解空间表示方法