当前位置:   article > 正文

代码随想录算法训练营day25 | 216.组合总和III、17.电话号码的字母组合

代码随想录算法训练营day25 | 216.组合总和III、17.电话号码的字母组合

216.组合总和III

剪枝,和组合题目类似

  1. class Solution:
  2. def __init__(self):
  3. self.result = []
  4. self.path = []
  5. def backtracking(self, k, n, startIndex):
  6. if len(self.path) == k:
  7. if sum(self.path) == n:
  8. self.result.append(self.path[:])
  9. else:
  10. return
  11. for i in range(startIndex, 10):
  12. self.path.append(i)
  13. self.backtracking(k, n, i+1)
  14. self.path.pop()
  15. def combinationSum3(self, k: int, n: int) -> List[List[int]]:
  16. self.backtracking(k, n, 1)
  17. return self.result

剪枝,并且优化了求和操作

  1. class Solution:
  2. def __init__(self):
  3. self.result = []
  4. self.path = []
  5. def backtracking(self, k, n, sum, startIndex):
  6. if sum > n:
  7. return
  8. if len(self.path) == k:
  9. if sum == n:
  10. self.result.append(self.path[:])
  11. else:
  12. return
  13. for i in range(startIndex, 9-(k-len(self.path))+2):
  14. self.path.append(i)
  15. sum += i
  16. self.backtracking(k, n, sum, i+1)
  17. self.path.pop()
  18. sum -= i
  19. def combinationSum3(self, k: int, n: int) -> List[List[int]]:
  20. self.backtracking(k, n, 0, 1)
  21. return self.result

17.电话号码的字母组合

没做出来,看题解学习

  1. class Solution:
  2. def __init__(self):
  3. self.letterMap = [
  4. "",
  5. "",
  6. "abc",
  7. "def",
  8. "ghi",
  9. "jkl",
  10. "mno",
  11. "pqrs",
  12. "tuv",
  13. "wxyz"
  14. ]
  15. self.result = []
  16. self.s = ''
  17. def backtracking(self, digits, index):
  18. if len(digits) == index:
  19. self.result.append(self.s)
  20. return
  21. for i in self.letterMap[int(digits[index])]:
  22. self.s += i
  23. index += 1
  24. self.backtracking(digits, index)
  25. index -= 1
  26. self.s = self.s[:-1]
  27. def letterCombinations(self, digits: str) -> List[str]:
  28. if len(digits) == 0:
  29. return self.result
  30. self.backtracking(digits, 0)
  31. return self.result

结果字符改为列表

  1. class Solution:
  2. def __init__(self):
  3. self.letterMap = [
  4. "",
  5. "",
  6. "abc",
  7. "def",
  8. "ghi",
  9. "jkl",
  10. "mno",
  11. "pqrs",
  12. "tuv",
  13. "wxyz"
  14. ]
  15. self.result = []
  16. self.s = []
  17. def backtracking(self, digits, index):
  18. if len(digits) == index:
  19. self.result.append("".join(self.s))
  20. return
  21. for i in self.letterMap[int(digits[index])]:
  22. self.s.append(i)
  23. self.backtracking(digits, index+1)
  24. self.s.pop()
  25. def letterCombinations(self, digits: str) -> List[str]:
  26. if len(digits) == 0:
  27. return self.result
  28. self.backtracking(digits, 0)
  29. return self.result

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/526879
推荐阅读
相关标签
  

闽ICP备14008679号