【leetcode刷提筆記】Permutations

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   資料   

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

 

用深度搜尋的方法搜尋下面的一棵樹(樣本,非完整的樹),每次搜尋到葉子時經過的路徑就是一個排列。

    

代碼如下:

 1 public class Solution { 2     public List<List<Integer>> permute(int[] num) { 3         List<List<Integer>> answerList = new ArrayList<List<Integer>>(); 4         ArrayList<Integer> currentList = new ArrayList<Integer>(); 5         boolean[] visited = new boolean[num.length]; 6         DS(answerList, visited, num, currentList);         7         return answerList; 8     } 9     10     public void DS(List<List<Integer>> answerList,boolean[] visited,int[] num,ArrayList<Integer> currentList){11         boolean find = true;12         for(int i = 0;i < num.length;i++){13             if(!visited[i]){14                 currentList.add(num[i]);15                 visited[i]= true;16                 DS(answerList, visited, num, currentList);17                 visited[i]= false;18                 currentList.remove(currentList.size()-1);19                 find = false;20             }21         }22         if(find){23             ArrayList <Integer> temp = new ArrayList<Integer>(currentList);24             answerList.add(temp);25         }26     }27 }

上述代碼中DS函數為遞迴深度優先搜尋函數,answerList記錄最終得到的所有排列,visited資料記錄在某個時間點對應節點是否在訪問過的路徑上,currentList為當前走過的路徑。要注意的一點是找到一條新的路徑後,要為這條路徑申請記憶體空間存放它(代碼第23行所示),否則currentList被修改的時候已經存放到answerList中的排列也會被修改。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.