日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

46. Permutations

發布時間:2023/12/10 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 46. Permutations 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 1題目理解
  • 2 回溯
  • 3 47. Permutations II

1題目理解

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
輸入:整數數組nums,所有元素不相同
輸出:數組的所有可能的排列

例如:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

2 回溯

所有排列是指nums中的每一個元素,在每個位置都會出現一次。
有一個長度為n的空數組,第0位元素可能是1、2、3任意一個。第1位也一樣。但是這里前面的位置選了的元素,在后面位置就不能使用了。所以,我們可以用一個數組記錄哪些元素已經被使用過。

class Solution {private List<List<Integer>> answer;private boolean[] visited;private int[] nums;public List<List<Integer>> permute(int[] nums) {answer = new ArrayList<List<Integer>>();this.nums = nums;visited = new boolean[nums.length];dfs(0,new int[nums.length]);return answer;}private void dfs(int index,int[] items){if(index == this.nums.length){List<Integer> list = new ArrayList<Integer>();for(int n : items){list.add(n);}answer.add(list);return;}for(int i =0;i<nums.length;i++){if(!visited[i]){visited[i] = true;items[index] = nums[i];dfs(index+1,items);visited[i]=false;}}} }

時間復雜度O(n?n!)O(n*n!)O(n?n!)。首先dfs調用次數是n!。在最后結果放入結果集有一個拷貝操作n。所以最終是O(n?n!)O(n*n!)O(n?n!)

3 47. Permutations II

與46類似,但是輸入nums可能包含重復元素。
例如:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
分析:重復元素之前有處理經驗了。對數組先排序。
對于第0個位置的元素可能是1、2。選擇了第一個1,第二個1就可以跳過了。否則就重復了。
代碼只要在之前代碼上改一下即可。

class Solution {private List<List<Integer>> answer;private boolean[] visited;private int[] nums;public List<List<Integer>> permuteUnique(int[] nums) {answer = new ArrayList<List<Integer>>();Arrays.sort(nums);this.nums = nums;visited = new boolean[nums.length];dfs(0,new int[nums.length]);return answer;}private void dfs(int index,int[] items){if(index == this.nums.length){List<Integer> list = new ArrayList<Integer>();for(int n : items){list.add(n);}answer.add(list);return;}for(int i = 0;i<nums.length;i++){if(!visited[i]){visited[i] = true;items[index] = nums[i];dfs(index+1,items);visited[i]=false;while(i+1<nums.length && nums[i+1]==nums[i]) i++;}}} }

時間復雜度最壞情況下上O(n?n!)O(n*n!)O(n?n!)。首先dfs調用次數是n!。在最后結果放入結果集有一個拷貝操作n。所以最終是O(n?n!)O(n*n!)O(n?n!)

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的46. Permutations的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。