LeetCode 46.全排列 dfs遞迴套路版
阿新 • • 發佈:2019-02-09
給定一個沒有重複數字的序列,返回其所有可能的全排列。
示例:
輸入: [1,2,3]
輸出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路:在java程式碼裡面
java版:
class Solution { public static List<List<Integer>> ans = new ArrayList<List<Integer>>();//儲存總答案 public static int[] path = new int[100];//小答案 public static boolean[] v = new boolean[100];//標記是否用過 //dfs套路,輸入裡面一般都有index表示你輸入到哪裡了,可以指引你從哪裡開始,什麼時候結束 public static void robot(int idx,int[] nums){ //只要是遞迴第一行永遠是邊界條件判斷,有時候會記錄結果 if (idx >= nums.length){ //記錄ans List<Integer> tmp = new ArrayList<Integer>(); for (int i = 0 ; i < nums.length; i++){ tmp.add(nums[path[i]]); } ans.add(tmp); return; } //全排列 for (int i = 0;i< nums.length;i++){ if (v[i] == false){ path[idx] = i;//記錄陣列的下標 v[i] = true; robot(idx+ 1,nums); //遞迴一次,加一層[1,2,3] v[i] = false; } } } public List<List<Integer>> permute(int[] nums) { ans.clear(); robot(0,nums); return ans; } }
# class Solution: # def permute(self, nums): # """ # :type nums: List[int] # :rtype: List[List[int]] # """ # """ # [a,b,c]的全排列== a+[b,c],b+[a,c],c +[a,b]的全排列 # """ # if len(nums) <= 1: # return [nums] # ans = [] # for i, num in enumerate(nums): # n = nums[:i] + nums[i+1:] # n是剩餘數的list # for y in self.permute(n): # 直到函式有return,一個數的時候[nums],所以y是list # ans.append([num] + y) # return ans class Solution: def permuteHelper(self, nums, pos, res, lists, visited): if len(lists) == len(nums): res.append(lists[:]) for i in range(len(nums)): if visited[i]: continue visited[i] = True lists.append(nums[i]) self.permuteHelper(nums, i + 1, res, lists, visited) lists.remove(nums[i]) visited[i] = False def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() res = [] visited = [False] * len(nums) self.permuteHelper(nums, 0, res, [], visited) return res