Leetcode46. Permutations
这道题是backtracking的。
看题会先想,这暴力解法多个循环不就做出来了?然后细想发现并不可以,因为要用多少个循环是由nums数组长度决定的。
这种情况下都要考虑使用backtracking(DFS)。
backtracking整体参考leetcode39 Combination Sum 。
1 class Solution { 2 public List<List<Integer>> permute(int[] nums) { 3 List<List<Integer>> ans = new ArrayList<>(); 4 helper(ans,new ArrayList<Integer>(),nums); 5 return ans; 6 } 7 private void helper(List<List<Integer>> ans,List<Integer> tempList,int[] nums){ 8 if(tempList.size()==nums.length) ans.add(new ArrayList<>(tempList)); 9 else{ 10 for(int i=0;i<nums.length;i++){ 11 if(tempList.contains(nums[i])) continue; 12 tempList.add(nums[i]); 13 helper(ans,tempList,nums); 14 tempList.remove(tempList.size()-1); 15 } 16 } 17 } 18 }
3ms,74.25%。可以了。
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: if nums is None or len(nums)<1: return [] ans = [] self.helper(nums,ans,0) return ans def helper(self,nums,ans,idx): if idx == len(nums)-1: ans.append(nums[:]) return for i in range(idx,len(nums)): temp = nums[idx] nums[idx] = nums[i] nums[i] = temp self.helper(nums,ans,idx+1) temp = nums[idx] nums[idx] = nums[i] nums[i] = temp
Runtime: 44 ms, faster than 90.30% of Python3 online submissions forPermutations.
Memory Usage: 13.8 MB, less than 5.38% of Python3 online submissions for Permutations.

浙公网安备 33010602011771号