Permutations I

Given a collection of distinct integers, return all possible
permutations.

Example:

Input: [1,2,3]
Output: [
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1] ]

思路

回溯法, 这里因为每次要从i= 0开始遍历(如果还继续用i = index, 就只会有[1,2,3] 而[2,1,1],[3,2,1]的情况就会错过)
所以要维护一个列表, 确认每个数是否被访问过

复杂度

时间O(n!) 空间O(n)

代码

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        List<Integer> tmp = new ArrayList<>();
        boolean[] visit = new boolean[nums.length];
        dfs(nums, tmp, res, visit);
        return res;
    }
   private void dfs(int[] nums, List<Integer> tmp, List<List<Integer>> res,  boolean[] visit) {
        if (tmp.size() == nums.length) {
            res.add(new ArrayList<>(tmp));
            return;
        }
       for (int i =0; i < nums.length; i++) {
           if (visit[i]) {
               continue;
           }
           tmp.add(nums[i]);
           visit[i] = true;
           dfs(nums, tmp, res, visit);
           tmp.remove(tmp.size() - 1);
           visit[i] = false;
       }
   
   }
}

Permutations II

思路

这里因为会有重复情况, 所以要先排序 然后确认当前数和前一个数相同且前一个数没有被访问的情况下跳过.

复杂度

时间O(n!) 空间O(n)

代码

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

lpy1990
26 声望10 粉丝

引用和评论

0 条评论