You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:生成每位数字仅±1的全组合方法(以123456为例)

生成数字串每位加减1的所有组合方案

核心逻辑确认

你推测的组合总数为2^N完全正确——因为每位数字有且仅有2种操作选择(加1或减1),N位数字的总组合数就是2的N次方。

两种实现方式

1. 递归实现

递归的思路是拆分问题:每次处理当前第一位数字,生成其加1、减1的两种结果,再递归处理剩余的数字串,最后将当前位的两种可能与剩余部分的所有组合拼接,得到最终结果。

def generate_combinations(s):
    if not s:
        return [""]
    current_digit = int(s[0])
    # 生成当前位的两种操作结果
    opt_plus = str(current_digit + 1)
    opt_minus = str(current_digit - 1)
    # 递归处理剩余数字串
    rest_combs = generate_combinations(s[1:])
    # 拼接所有组合
    result = []
    for opt in [opt_plus, opt_minus]:
        result.extend([opt + comb for comb in rest_combs])
    return result

# 测试示例
input_str = "123456"
all_combs = generate_combinations(input_str)
print(f"总组合数:{len(all_combs)}")
# 打印前5个结果示例
for comb in all_combs[:5]:
    print(comb)

2. 迭代实现

如果不习惯递归,可以用迭代方式逐步构建结果:从空字符串开始,逐个处理每一位数字,将现有结果分别与当前位的两种操作结果拼接,更新结果列表直到所有位处理完成。

def generate_combinations_iter(s):
    combinations = [""]
    for char in s:
        digit = int(char)
        new_combs = []
        # 对每个现有组合,追加当前位的两种可能
        for comb in combinations:
            new_combs.append(comb + str(digit + 1))
            new_combs.append(comb + str(digit - 1))
        combinations = new_combs
    return combinations

# 测试示例
input_str = "123456"
all_combs = generate_combinations_iter(input_str)
print(f"总组合数:{len(all_combs)}")
for comb in all_combs[:5]:
    print(comb)

可选扩展:数字循环处理

如果需要实现数字循环(比如0减1变为9,9加1变为0),只需修改数字计算逻辑为取模运算:

# 加1循环:(数字 + 1) % 10
# 减1循环:(数字 - 1) % 10(Python中负数取模自动转为正)
opt_plus = str((current_digit + 1) % 10)
opt_minus = str((current_digit - 1) % 10)

内容的提问来源于stack exchange,提问作者bronzecoder909

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 07:31:06