Leetcode summary: backstrack problem

46. Permutations

Given a collection of distinct integers, return all possible permutations.

Example:

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]]
        """
        ret=[]
        tmp=[]
        def dfs(nums,tmp):
            if len(tmp)==len(nums):
                ret.append(tmp[:])
                return 
            for i in nums:
                if i in tmp:
                    continue
                tmp.append(i)
                dfs(nums,tmp)
                tmp.pop()
                
        dfs(nums,tmp)
        return ret

47. Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        ret=[]
        tmp=[]
        
        def dfs(nums):
            for i in range(len(nums)):
                if len(tmp)==len(nums):
                    ret.append(tmp[:])
                    return
                
                if visited[i]==1 or (i>0  and nums[i]==nums[i-1] and visited[i-1]==0):
                    continue
                visited[i]=1
                tmp.append(nums[i])
                dfs(nums)
                tmp.pop()
                visited[i]=0

        nums.sort()
        visited=[0] * len(nums)
        dfs(nums)
        return ret

optimize solution:

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        ans = []
        def shouldSwap(nums, start, end):
            for i in range(start, end):
                if nums[i] == nums[end]:
                    return False
            return True
        
        def helper(nums, index):
            if index == len(nums) - 1:
                ans.append(list(nums))
            for i in range(index, len(nums)):
                if shouldSwap(nums, index, i):
                    nums[index], nums[i] = nums[i], nums[index]
                    helper(nums, index + 1)
                    nums[index], nums[i] = nums[i], nums[index]
        #nums.sort()
        helper(nums, 0)
        return ans

60. Permutation Sequence

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

“123”
“132”
“213”
“231”
“312”
“321”
Given n and k, return the kth permutation sequence.

Note:

Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:

Input: n = 3, k = 3
Output: “213”
Example 2:

Input: n = 4, k = 9
Output: “2314”

#
# @lc app=leetcode id=60 lang=python
#
# [60] Permutation Sequence
#
class Solution(object):
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        s="123456789"
        ret=""
        f=[1 for i in range(n)]

        for i in range(1,n):
            f[i]=f[i-1]*i
        
        k=k-1
        for i in range(n,0,-1):
            j=k/f[i-1]
            ret=ret+s[j]
            k=k%f[i-1]
            if j==len(s)-1:
                s=s[:j]
            else:
                s=s[:j]+s[j+1:]

        return ret

77. Combinations

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        def backtrack(first = 1, curr = []):
            # if the combination is done
            if len(curr) == k:  
                output.append(curr[:])
            for i in range(first, n + 1):
                # add i into the current combination
                curr.append(i)
                # use next integers to complete the combination
                backtrack(i + 1, curr)
                # backtrack
                curr.pop()
        
        output = []
        backtrack()
        return output

subset

#
# @lc app=leetcode id=78 lang=python
#
# [78] Subsets
#
class Solution(object):
    def subsets(self, nums):
        def backtrack(start, end, tmp):
            ans.append(tmp[:])
            for i in range(start, end):
                tmp.append(nums[i])
                backtrack(i+1, end, tmp)
                tmp.pop()
        ans = []
        backtrack(0, len(nums), [])
    
        return ans

90. Subsets II

#
# @lc app=leetcode id=90 lang=python
#
# [90] Subsets II
#
class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        out=[]
        ret=[]
        def helper(nums,out,s,ret): 
            ret.append(out[:])
            for i in range(s,len(nums)):
                if i>s and nums[i]==nums[i-1]:
                    continue
                out.append(nums[i])
                helper(nums,out,i+1,ret)
                out.pop()
        nums.sort()
        helper(nums,out,0,ret)
        return ret

and also:

class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        def helper(nums,out,b):
            ret.append(out[:])
            
            seen=set()
            for i in range(b,len(nums)):
                if nums[i] not in seen:
                    seen.add(nums[i])
                    out.append(nums[i])
                    helper(nums,out,i+1)
                    #seen.remove(i)
                    out.pop()

        ret=[]
        out=[]
        nums.sort()
        helper(nums,out,0)
        return ret
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章