遞歸應用-全排列

leetcode題

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums.length == 0) return  result;
        if (nums.length == 1) {
            List<Integer> l = new LinkedList<>();
            l.add(nums[0]);
            result.add(l);
            return  result;
        }


        for(int i=0; i<nums.length; ++i) {
            int[] tmp = new int[nums.length-1];
            if (i>0) {
                System.arraycopy(nums, 0, tmp, 0, i);
            }
            if (i<nums.length-1) {
                System.arraycopy(nums, i+1, tmp, i, nums.length-1-i);
            }

            List<List<Integer>> r = permute(tmp);
            for(List<Integer> l: r) {
                l.add(0, nums[i]);
            }
            result.addAll(r);
        }

        return result;
        
    }
}

如果輸入數組參數中有重複元素,並且結果中要求去除重複排列,可在循環中用set記錄下已處理過的元素。

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums.length == 0) return  result;
        if (nums.length == 1) {
            List<Integer> l = new LinkedList<>();
            l.add(nums[0]);
            result.add(l);
            return  result;
        }

        Set<Integer> set = new HashSet<>();
        for(int i=0; i<nums.length; ++i) {
            if (set.contains(nums[i])) continue; 		//已處理過,skip

            int[] tmp = new int[nums.length-1];
            if (i>0) {
                System.arraycopy(nums, 0, tmp, 0, i);
            }
            if (i<nums.length-1) {
                System.arraycopy(nums, i+1, tmp, i, nums.length-1-i);
            }

            List<List<Integer>> r = permuteUnique(tmp);
            for(List<Integer> l: r) {
                l.add(0, nums[i]);
            }
            result.addAll(r);
            set.add(nums[i]);
        }

        return result;
    }

}
發佈了95 篇原創文章 · 獲贊 48 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章