Permutations

Problem:


Given a collection of distinct 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],
  [3,2,1]
]
3/23/2018 update:

The above diagram shows how permutation is generated. In order to expand parent node, we need to pick up the numbers that haven't been used.

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res=new ArrayList<>();
        
        if(nums==null || nums.length == 0) {
            return null;
        }
       
        helper(res, new ArrayList<>(), nums);
        return res;
    }
    
   private void helper(List<List<Integer>> res, List<Integer> list, int[] nums) {
        if (list.size() == nums.length) {
            res.add(new ArrayList<>(list));
        }

        for (int n: nums) {
            if (list.contains(n)) continue;
            list.add(n);
            helper(res, list, nums);
            list.remove(list.size() - 1);
        }
    }
}


1/23/2018
No need to use extra space, list itself has the contains method.

1/22/2018
第二遍做居然one pass, 说明刷得越多越熟练效率越高。这给我刷题带来了极大地信心。居然能自己想到用set, 然后传递set的时候deep copy。因为第一遍已经搞忘了,所以相当于自己想出来的。

Solution:
class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res=new ArrayList<>();
        
        if(nums==null || nums.length == 0) {
            return null;
        }
        
        Set<Integer> set = new HashSet<>();
        for (int n: nums) {
            set.add(n);
        }
        search(new ArrayList<>(), res, set);
        return res;
    }
    
    private void search(List<Integer> permutation, List<List<Integer>> res, Set<Integer> set)
    {
        if (set.size() == 0) 
        {
            res.add(new ArrayList<>(permutation));
            return;
        }
        
        for(int n: set) {
            permutation.add(n);
            Set<Integer> tempSet = new HashSet<>(set);
            tempSet.remove(n);
            search(permutation, res, tempSet);
            permutation.remove(permutation.size() - 1);
        }
    }
}

--------------------------------------------------------------------------------------------------------------------------

思路:
DFS, 每往下走一层需要剔除之前走过的数,所以用一个set来保存可以排列的数。比如1,2,3, 先排了1, 就暂时把1踢出,下一位就剩2,3了。

实现:
DFS的答案只有一个List<T> reference。

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List