1. 程式人生 > >[刷題] dfs回溯 合集

[刷題] dfs回溯 合集

題目: Permutations

Input: [1,2,3]

Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]

def Permutations (nums):
	ans = []
	dfs(nums,[],ans)
	return ans
	
def dfs(nums, tmp, ans):
	if not nums:
		#if tmp not in ans:當陣列中有相同的元素時
			ans.append(tmp)
			return 
	for i in range(len(nums)):
		dfs(
nums[:i]+nums[i+1:], tmp+[nums[i]], ans)⭐️

題目:

Given two integers n and k, return all possible combinations of k numbers out of 1 … n. 返回k個數的組合.

Example:

Input: n = 4, k = 2 Output: [[2,4], [3,4],[2,3], [1,2], [1,3], [1,4]]


class Solution(object):
    def combine(self, n, k):
        ans=[]
        self.
dfs(n,1,k,[],ans) return ans def dfs(self,n,start,k,ret,ans): if k <= 0 : ans.append(ret) else: for i in range(start,n+1): self.dfs(n,i+1,k-1,ret+[i],ans)

題目:

子集: Input: nums = [1,2,3] Output: [[3], [1], [2], [1,2,3], [1,3],[2,3], [1,2],[] ]

#1
def subset_recursive(nums):
    ans = []
    dfs(nums, 0, [], ans)
    return ans


def dfs1(nums, start, ret, ans):
    ans.append(ret)
    for i in range(start, len(nums)):
        dfs(nums, i + 1, ret + [nums[i]], ans)
   
 #2 點陣圖
 class Solution(object):
    def subset1(self, nums):
        nums_ = pow(2,len(nums))
        ans= [ []for _ in range(nums_)]
        for i in range(len(nums)):
          for j in range(nums_):
            if (j>>i) & 1:
              ans[j].append(nums[i])
        return ans
       

帶有重複元素的子集:

    def subsetsWithDup(self, nums):
        res = []
        nums.sort()  #!!! 先排序
        self.dfs(nums, 0, [], res)
        return res

    def dfs(self, nums, index, path, res):
        res.append(path)
        for i in range(index, len(nums)):
            if i > index and nums[i] == nums[i - 1]:⭐️
                continue
            self.dfs(nums, i + 1, path + [nums[i]], res)

題目:組合數的和

Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,2,2], [5] ]

class Solution:
  
    def combinationSum2(self, nums, target):
        ans = []
        nums.sort()
        print(nums[:])
        self.dfs(nums, target, 0, [], ans)
        return ret

    def dfs(self, nums, target, start, path, ans):
        if target == 0 :
            ans.append(path)
            return
        for i in range(start, len(nums)):
            if nums[i] > target:
                break
            if i > start and nums[i] == nums[i-1]:
                continue
            self.dfs( nums, target - nums[i], i + 1, path + [nums[i]], ans )
            

題目: N皇后問題

class Solution(object):
    def solveNQueens(self, n):
    
        res = []
        columnforRow = [n]*n
        self.dfs(n,0,columnforRow,res)
        return res

    def dfs(self, n, row, columnforRow,ret):
        #back
        if row == n:
            item = []
            for i in range(n):
                rowstr = ""
                for j in range(n):
                    if columnforRow[i] == j:
                        rowstr += 'Q'
                    else:
                        rowstr += '.'
                item.append(rowstr)
            ret.append(item)
            return
		
        for i in range(n):
            columnforRow[row] = i  ⭐️
            if self.check(row,columnforRow) :
                self.dfs(n,row + 1,columnforRow,ret)
        #track

    def check (self, row, columnforRow):
        for i in range(row):
            if(columnforRow[row] == columnforRow[i] or abs(columnforRow[row]-columnforRow[i]) == row - i):
                return False
        return True