回溯算法

回溯算法

回溯算法本质上就是枚举,它可能适合应用于缺乏规律,或我们还不了解其规律的搜索场景中.

求解一般模式

  1. 找到每一步求解时的状态;
  2. 更新状态,使用新状态求解;
  3. 查看是否可以通过条件提前终止搜索;(剪枝)

每个数组取一个值进行组合

例如,输入 ['a1','a2'],['b1','b2','b3'],期望输出['a1','b1'],['a1','b2'],['a1','b3'],['a2','b1'],['a2','b2'],['a2','b3']

求解过程如下图:

代码如下:

def combine1(*lists):
    res = []

    def search(value, index):
        if len(value) == len(lists):
            res.append(copy.deepcopy(value))
            return

        for item in lists[index]:
            value.append(item)
            search(value,index+1)
            value.pop()

    search([],0)
    return res

if __name__ == "__main__":
    l1 = ['a1','a2']
    l2 = ['b1','b2','b3']
    res = combine1(l1,l2)
    print(res) # [['a1', 'b1'], ['a1', 'b2'], ['a1', 'b3'], ['a2', 'b1'], ['a2', 'b2'], ['a2', 'b3']]

从一个数组中取 n 个数求组合

求解过程如下图:

代码如下:

def combine(li, num):
    res = []

    def search(value,index):
        if len(value) == num:
            res.append(value)
            return

        for (ind,item) in enumerate(li[index:]):
            search(f"{value}{item}",index+ind+1)

    search('',0)
    return res


res = combine(['1','2','3','4','5'],3)

print(res) # ['123', '124', '125', '134', '135', '145', '234', '235', '245', '345']
原文地址:https://www.cnblogs.com/aloe-n/p/12513535.html