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 閱讀(1550) 評論(1)  編輯  收藏 所屬分類: Leetcode

          評論

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

          主站蜘蛛池模板: 稷山县| 禄丰县| 泾阳县| 汉川市| 平原县| 垣曲县| 霍山县| 连平县| 瓮安县| 怀柔区| 香港 | 上栗县| 建湖县| 南宁市| 新丰县| 麦盖提县| 财经| 赣榆县| 屏南县| 大庆市| 于都县| 吉林市| 河北省| 保定市| 邮箱| 南宁市| 宜阳县| 苗栗县| 涪陵区| 磐安县| 阿坝县| 达拉特旗| 盐边县| 正蓝旗| 金阳县| 积石山| 襄垣县| 胶州市| 兖州市| 犍为县| 岗巴县|