Backtracking 编程范式python

本文介绍了回溯编程的基本思想,包括选择、探索和撤销的范式,并通过两个实例展示了如何使用回溯法解决排列问题和掷骰子求组合问题。还提及了可以通过剪枝优化来提高算法效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 choose-> explore-> unchoose paradigm is the key! below is the general pseudo code

 来看看例子一:Given a collection of distinct integers, return all possible permutations.

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if not nums:      #sanity check
            return []
        
        res = []
        self.helper(nums, res, [])
        return res
    
    def helper(self, nums, res, item):   #explore
        if len(item) == len(nums):
            res.append(item[:]) #为什么要item[:]可以去研究研究python的参数传入
            return
        
        for num in nums:
            if num not in item:
                item.append(num)  #choose
                print item # put a print here just to give a hint of why we need to unchoose,you can see the item list growing and shrinking
                self.helper(nums, res, item)  #explore recursively
                item.pop()      #unchoose

再来看个例子:给定掷骰子的次数,再给定目标和,输出所有点数和等于目标和的组合

class Solution(object):
    def diceSum(self, num, sum):
        res = []
        self.helper(num, sum, res, [])
        return res
 
    def helper(self, num, sum, res, path):
        if num == 0:
            if sum == 0:
                res.append(path[:]) #path[:]就相当于Java里的new ArrayList(path),新内存
                return
            return
        for i in xrange(1,7):
            path.append(i)   #choose
            self.helper(num-1, sum-i, res, path)  #explore
            path.pop()    #unchoose

上面的程序可以解决问题,可是还不完美,我们可以进行剪枝优化,这里代码就不列出了。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值