IT技術小屋

          秋風秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評論 :: 0 Trackbacks
          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 PermutationsII {
           2     public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
           3         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
           4         permuteUnique(num, 0, result);
           5         return result;
           6     }
           7 
           8     void permuteUnique(int[] num, int begin,
           9             ArrayList<ArrayList<Integer>> result) {
          10         if (begin > num.length - 1) {
          11             ArrayList<Integer> item = new ArrayList<Integer>();
          12             for (int h = 0; h < num.length; h++) {
          13                 item.add(num[h]);
          14             }
          15             result.add(item);
          16         }
          17         for (int end = begin; end < num.length; end++) {
          18             if (isSwap(num, begin, end)) {
          19                 swap(num, begin, end);
          20                 permuteUnique(num, begin + 1, result);
          21                 swap(num, begin, end);
          22             }
          23         }
          24     }
          25 
          26     boolean isSwap(int[] arr, int i, int j) {
          27         for (int k = i; k < j; k++) {
          28             if (arr[k] == arr[j]) {
          29                 return false;
          30             }
          31         }
          32         return true;
          33     }
          34     
          35     private void swap(int[] a, int i, int j) {
          36         int tmp = a[i];
          37         a[i] = a[j];
          38         a[j] = tmp;
          39     }
          40 }
          posted on 2013-12-20 15:30 Meng Lee 閱讀(1552) 評論(1)  編輯  收藏 所屬分類: Leetcode

          評論

          # re: [Leetcode] Permutations II 2013-12-21 13:24 零柒鎖業
          支持博主分享  回復  更多評論
            

          主站蜘蛛池模板: 琼中| 乌拉特中旗| 巴东县| 介休市| 翁牛特旗| 乌什县| 府谷县| 安庆市| 稻城县| 融水| 长垣县| 上林县| 和政县| 中超| 濉溪县| 鹰潭市| 昌邑市| 泌阳县| 咸丰县| 黄浦区| 明溪县| 黑河市| 东辽县| 沽源县| 类乌齐县| 全州县| 黎平县| 德庆县| 涟水县| 伊宁县| 安阳市| 老河口市| 平乐县| 彭泽县| 台中县| 广东省| 石楼县| 黄梅县| 曲水县| 柳河县| 鹤壁市|