IT技術(shù)小屋

          秋風(fēng)秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            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].

          數(shù)組全排列題目,基本思想是對每一個字符與后面的字符作交換,以生成新的序列。為了防止重復(fù),交換之前需要檢查之前是否已經(jīng)和同樣的字符串做過交換。代碼如下:
           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 閱讀(1557) 評論(1)  編輯  收藏 所屬分類: Leetcode

          評論

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

          主站蜘蛛池模板: 分宜县| 家居| 隆林| 江城| 揭东县| 肃宁县| 文安县| 永昌县| 鸡泽县| 巴青县| 肇东市| 庆云县| 萨迦县| 民勤县| 应用必备| 鄱阳县| 镇平县| 白山市| 深圳市| 临夏县| 锡林浩特市| 红河县| 灌阳县| 湖北省| 凌源市| 缙云县| 固安县| 綦江县| 大洼县| 河西区| 甘孜县| 巴彦县| 富顺县| 乐亭县| 黄平县| 武汉市| 陆丰市| 丰宁| 都兰县| 伊宁县| 德惠市|