Skip to content

Latest commit

 

History

History
123 lines (107 loc) · 2.54 KB

47.全排列2.md

File metadata and controls

123 lines (107 loc) · 2.54 KB

47. 全排列 II

url

题目

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

方法

code

js

let permuteUnique = nums => {
    let ret = []
    if (nums === null || nums.length === 0) return ret;
    let marked = Array(nums.length).fill(false);
    let dfs = (nums, list) => {
        if (list.length === nums.length) {
            ret.push(list.slice());
            return;
        }
        for (let i = 0; i < nums.length; i++) {
            if (marked[i]) continue;
            if (i !== 0 && nums[i] === nums[i - 1] && !marked[i - 1]) continue;
            list.push(nums[i]);
            marked[i] = true;
            dfs(nums, list);
            marked[i] = false;
            list.pop();
        }
    }
    nums.sort((a, b) => {return a - b})
    dfs(nums, []);
    return ret;
}

go

func permuteUnique(nums []int) [][]int {
	var res [][]int
	if len(nums) == 0 {
		return res
	}
	var dfs func(nums []int, list []int)
	marked := make([]bool, len(nums))
	dfs = func(nums []int, list []int) {
		if len(nums) == len(list) {
			res = append(res, append([]int{}, list...))
		}
		for i := 0; i < len(nums); i++ {
			if marked[i] {
				continue
			}
			if i != 0 && nums[i] == nums[i-1] && !marked[i-1] {
				continue
			}
			list = append(list, nums[i])
			marked[i] = true
			dfs(nums, list)
			marked[i] = false
			list = list[0:len(list) - 1]
		}
	}
	sort.Ints(nums)
	dfs(nums, []int{})
	return res
}

java

class Solution {
    private List<List<Integer>> ret = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        if (nums == null || nums.length == 0)
            return ret;
        boolean[] marked = new boolean[nums.length];
        Arrays.sort(nums);
        dfs(nums, marked, new ArrayList());
        return ret;
    }   
    private void dfs(int[] nums, boolean[] marked, ArrayList<Integer> list) {
        if (list.size() == nums.length) {
            ret.add(new ArrayList(list));
            return;
        }   
        for (int i = 0; i < nums.length; i++){
            if (marked[i])
                continue;
            if (i != 0 && nums[i] == nums[i - 1] && !marked[i - 1])
                continue;
            list.add(nums[i]);
            marked[i] = true;
            dfs(nums, marked, list);
            marked[i] = false;
            list.remove(list.size() - 1);
        }
    }
}