赞
踩
- class Solution:
- def __init__(self):
- self.path = []
- self.result = []
- self.ans = []
-
-
- def combinationSum3(self, k: int, n: int) -> List[List[int]]:
- temp = self.bcktracking(9, k, 1)
- for j in range(len(temp)):
- if sum(temp[j]) == n:
- self.ans.append(temp[j])
- return self.ans
-
- def bcktracking(self, nums, k, startindex):#step1
- #step2
- if len(self.path) == k:
- self.result.append(self.path[:])
- return
- #step3
- for i in range(startindex, (nums-(k-len(self.path))+1)+1):#剪枝
- self.path.append(i)
- self.bcktracking(nums, k, i+1)
- self.path.pop()
- return self.result
- class Solution:
- def __init__(self):
- self.path = []
- self.result = []
-
-
- def combinationSum3(self, k: int, n: int) -> List[List[int]]:
- return self.bcktracking(9, k, n, 1)
-
-
- def bcktracking(self, nums, k, n, startindex):#step1
- #step2
- if len(self.path) == k:
- if sum(self.path) == n:
- self.result.append(self.path[:])
- return
- #step3
- for i in range(startindex, (nums-(k-len(self.path))+1)+1):#类似#77剪枝
- self.path.append(i)
- self.bcktracking(nums, k, n, i+1)
- self.path.pop()
- return self.result
- class Solution:
- def __init__(self):
- self.path = []
- self.result = []
-
-
- def combinationSum3(self, k: int, n: int) -> List[List[int]]:
- return self.bcktracking(9, k, n, 1)
-
-
- def bcktracking(self, nums, k, n, startindex):#step1
- #step2
- if sum(self.path) > n:#剪枝
- return
-
- if len(self.path) == k:
- if sum(self.path) == n:
- self.result.append(self.path[:])
- return
- #step3
- for i in range(startindex, (nums-(k-len(self.path))+1)+1):#类似#77剪枝
- self.path.append(i)
- self.bcktracking(nums, k, n, i+1)
- self.path.pop()
- return self.result
- class Solution:
- def __init__(self):
- self.s = ''
- self.res = []
- self.map = {0:'', 1:'', 2:'abc', 3:'def', 4:'ghi', 5:'jkl', 6:'mno', 7:'pqrs', 8:'tuv', 9:'wxyz'}
-
-
- def letterCombinations(self, digits: str) -> List[str]:
- return self.backtracking(digits, 0)
-
- def backtracking(self, digits, index):#step1
- #step2
- if index == len(digits):
- self.res.append(self.s)
- return
- #step3
- chars = self.map[int(digits[index])]
- for char in chars:
- self.s += char
- self.backtracking(digits, index+1)
- self.s = self.s[:len(self.s)-1] #回溯,相当于数组pop()操作
-
- return self.res
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。