LeetCode第四十七題 Python實現

2021-10-25 17:09:59 字數 1255 閱讀 2621

title: leetcode no.47

categories:

tags:

給定乙個可包含重複數字的序列 nums ,按任意順序 返回所有不重複的全排列。

示例 1:

輸入:nums = [1,1,2]

輸出:[[1,1,2],

[1,2,1],

[2,1,1]]

示例 2:

輸入:nums = [1,2,3]

輸出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

1 <= nums.length <= 8

-10 <= nums[i] <= 10

本題和上一道題目異曲同工,只是新增乙個額外的重複檢測**。

class solution(object):

def permuteunique(self, nums):

""":type nums: list[int]

:rtype: list[list[int]]

核心思想:這裡python有現成的庫可以進行,但是為了能夠掌握**,這裡我使用回溯法進行編寫**

回溯法的框架:

def backtrack(path, selected):

if 滿足停止條件:

for 選擇 in 選擇列表:

做出選擇

遞迴執行backtrack

滿足則return true

如果不滿足要求就撤銷選擇

"""result =

temp =

def backtrack(nums):

if not nums: # 如果為空則表示選擇完畢

if temp in result:

return

else:

return

for i in range(len(nums)):

# 做出選擇

# 去除做出的選擇

tt = nums[:i]+nums[i+1:]

# 接著執行選擇

backtrack(tt)

# 撤銷選擇

temp.pop()

backtrack(nums)

return result

if __name__ == '__main__':

s = solution()

print(s.permuteunique([1,2,3]))

Leetcode第四十七題 全排列 II

題目 給定乙個可包含重複數字的序列,返回所有不重複的全排列。示例 輸入 1,1,2 輸出 1,1,2 1,2,1 2,1,1 個人思路 上一題加個去重,就多2行 官方答案推薦 差不多python class solution def permuteunique self,nums list int ...

第四十七題(求最長遞減子串行)

題目 求乙個陣列的最長遞減子串行比如的最長遞減子串行為 動態規劃經典題目。c includeusing namespace std namespace ms100p 47 的最長遞減子串行為 void printarray int dp,int data,int k int finddecrease...

最長遞減子串行 微軟面試100題 第四十七題

題目要求 求乙個陣列的最長遞減子串行 比如的最長遞減子串行為。實現 1 動態規劃,時間複雜度o n 2 include using namespace std const int n 8 int lis int a,int n int main void cout lis a,n endl retu...