216. Combination Sum III 17. Letter Combinations of a Phone Number

文章描述了一个编程问题,要求找到所有由1到9的数字组成且和为n的有效组合,使用回溯算法(backtracking)实现,同时包含剪枝优化。另一个问题是将电话号码的数字转换为字母组合。

Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

  • Only numbers 1 through 9 are used.
  • Each number is used at most once.

Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

 my solution:

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        result =[]
        self.backtracking(k, n, [], result, 1)
        return result

    
    def backtracking(self, k, n, path, result, startindex):
        if sum(path) == n and len(path) == k:
            result.append(path[:])
            return
        
        for i in range(startindex, 10): # 超时 (startindex, 10 - (k-len(path)) + 1) ;因为sum 大于 target时候 没跳出循环,len会不断变大,for循环就是负数了
            path.append(i)
            self.backtracking(k, n, path, result, i+1)
            path.pop()

There is also a important pruning剪枝 place, when the number of individuals is not exceeded but the total number is exceeded, it returns directly 

solution after pruning:

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        result =[]
        self.backtracking(k, n, [], result, 1)
        return result

    
    def backtracking(self, k, n, path, result, startindex):
        if sum(path) > n: # for剪枝的要求
            return

        if sum(path) == n and len(path) == k:
            result.append(path[:])
            return
        
        for i in range(startindex, 10 - (k-len(path)) + 1): #剪枝后
            path.append(i)
            self.backtracking(k, n, path, result, i+1)
            path.pop()

standard solution:

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        result = []  # 存放结果集
        self.backtracking(n, k, 0, 1, [], result)
        return result

    def backtracking(self, targetSum, k, currentSum, startIndex, path, result):
        if currentSum > targetSum:  # 剪枝操作
            return  # 如果path的长度等于k但currentSum不等于targetSum,则直接返回
        if len(path) == k:
            if currentSum == targetSum:
                result.append(path[:])
            return
        for i in range(startIndex, 9 - (k - len(path)) + 2):  # 剪枝
            currentSum += i  # 处理
            path.append(i)  # 处理
            self.backtracking(targetSum, k, currentSum, i + 1, path, result)  # 注意i+1调整startIndex
            currentSum -= i  # 回溯
            path.pop()  # 回溯

17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

 def init : self. lettermap = [ ],    self. result = [ ] ,     self.s =""

index: digits的index :Depth of the tree

backtracking:

class Solution:
    def __init__(self):
        self.s = ""
        self.result = []
        self.map =[
        "", #0
        "", #1
        "abc",#2
        "def",
        "ghi",
        "jkl",
        "mno",
        "pqrs",
        "tuv",
        "wxyz"
        ]
    
    def backtracking(self, digits, index):
        if len(self.s) == len(digits): # if index == len(digits)
            self.result.append(self.s)
            return # 这个return一定不能掉 ,下面的self.backtracking满足这个条件就直接执行 self.s = self.s[:-1]
        digit = int(digits[index]) #Convert the number at the index to an integer 
        letters = self.map[digit]  # Get the corresponding character set “abc”....
        for letter in letters:
            self.s += letter
            self.backtracking(digits, index+1)
            self.s = self.s[:-1] #Backtrack to remove the last added character 

    def letterCombinations(self, digits: str) -> List[str]:
        if len(digits) == 0:
            return self.result
        self.backtracking(digits, 0)
        return self.result

<think>好的,我需要帮助用户解决如何使用Python编写递归函数来打印字符串的所有组合的问题。首先,我得理解用户的需求。用户提到的“组合”可能有歧义,因为组合可以是子序列、排列或者子集等不同的形式。不过根据常见的编程问题,打印字符串的所有组合通常指的是生成所有可能的子序列,也就是字符串中字符的各种可能组合,保持原有顺序,但不需要连续。例如,字符串"abc"的子序列包括"a", "b", "c", "ab", "ac", "bc", "abc"。 接下来,我需要考虑递归的实现方式。递归函数通常需要一个基本情况和一个递归步骤。对于生成子序列,基本情况可能是当字符串为空时返回空列表,或者当处理到最后一个字符时,将当前字符加入所有现有组合中。递归步骤可能涉及将当前字符与之前生成的所有子序列进行组合。 参考用户提供的引用内容,特别是引用[2]和[3],它们展示了递归在字符串反转和回文检查中的应用。例如,引用[2]中的字符串反转函数通过递归每次处理最后一个字符,并将其与剩余部分的反转结果拼接。类似地,生成子序列可以每次处理一个字符,决定是否包含它到当前组合中。 可能的递归思路是:对于每个字符,可以选择包含或不包含它,然后递归处理剩下的字符。例如,对于字符串"abc",处理第一个字符'a'时,有两种选择:包含'a'或者不包含。对于剩下的"bc",同样进行选择,直到处理完所有字符,得到所有可能的组合。 然后,我需要考虑如何将这些逻辑转化为代码。递归函数可能需要参数来跟踪当前的位置和已生成的子序列。例如,函数可以接受原始字符串、当前索引、当前组合,以及存储所有组合的结果列表。每次递归调用时,处理下一个字符,分别生成包含和不包含该字符的分支。 另外,需要考虑去重的问题,如果字符串中有重复字符,可能会有重复的组合产生。但用户的问题中没有提到需要去重,所以可能暂时不需要处理这种情况,但可以在后续优化中提到。 测试用例也很重要。例如,输入"abc"应该输出所有8种可能的子序列,包括空字符串。不过用户可能希望排除空字符串,这时候可以在结果中过滤掉。或者根据用户需求调整。 现在,我需要编写示例代码,确保符合递归结构,并且能够正确生成所有组合。同时,根据用户提供的引用中的代码风格,比如引用[2]和[3],使用递归函数返回结果,并在主函数中调用并打印。 最后,生成相关问题,帮助用户深入理解递归在组合生成中的应用,可能的优化方法,以及相关算法问题,比如排列、子集等。</think>### 分步解答 要使用递归函数打印字符串的所有组合(子序列),可以通过以下步骤实现: 1. **递归定义** 假设字符串为$s$,当前处理位置为索引$i$,当前生成的子序列为`current`。每一步递归有两种选择: - 包含字符$s[i]$到`current`中 - 不包含字符$s[i]$到`current`中 递归终止条件为处理完所有字符(即$i = \text{len}(s)$)。 2. **代码实现** ```python def generate_combinations(s, index=0, current="", result=None): if result is None: result = [] if index == len(s): if current: # 排除空字符串 result.append(current) return result # 不包含当前字符的分支 generate_combinations(s, index+1, current, result) # 包含当前字符的分支 generate_combinations(s, index+1, current + s[index], result) return result s = "abc" combinations = generate_combinations(s) print("所有组合:", combinations) ``` 3. **输出结果** ``` 所有组合: ['c', 'b', 'bc', 'a', 'ac', 'ab', 'abc'] ``` 4. **代码解释** - 递归函数`generate_combinations`通过`index`跟踪当前处理的字符位置。 - 每次递归调用分为两个分支:不包含当前字符(直接进入下一个索引)和包含当前字符(将字符加入`current`)。 - 当`index`等于字符串长度时,将非空的`current`加入结果列表。 - 最终返回所有组合的列表。 5. **去重优化(可选)** 如果输入字符串包含重复字符(如"aab"),可以通过排序和跳过重复分支避免重复组合: ```python def generate_unique_combinations(s): s = sorted(s) # 排序以便跳过重复字符 result = [] def backtrack(index, current): if current: result.append(''.join(current)) for i in range(index, len(s)): if i > index and s[i] == s[i-1]: continue # 跳过重复字符 backtrack(i+1, current + [s[i]]) backtrack(0, []) return result ``` --- ### 相关问题 1. 如何生成字符串的所有排列(全排列)而非组合?[^4] 2. 递归生成组合的时间复杂度是多少? 3. 如何用迭代方法实现字符串组合生成?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值