[LeetCode] Permutations I / II

Permutations I

Problem

Given a list of numbers, return all possible permutations.

Example

For nums = [1,2,3], the permutations are:

[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

Challenge

Do it without recursion.

Solution

Recursion

class Solution {
    public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> num) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if (num == null || num.size() == 0) {
            return res;
        }
        ArrayList<Integer> list = new ArrayList<Integer> ();
        helper (nuts, list, res);
        return res;
    }
    
    public void helper(ArrayList<Integer> num, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> res) {
        if (list.size() == num.size()) {
            res.add(new ArrayList<Integer> (list));
            return;
        }
        for (int i = 0; i < num.size(); i++) {
            if (list.contains(num.get(i))) {
                continue;
            }
            list.add(num.get(i));
            helper(num, list, res);
            list.remove(list.size() - 1);
        }
    }
}

Permutations II

Problem

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

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

Solution

  1. sort
  2. call backtracking function in main function
  3. in backtracking function, when temp list size equals nums array size, save a copy of temp list to result
  4. iteration nums array, if current num is used, or it's same as previous num and previous num is unused (released), continue
  5. update temp array and used boolean array at the same time in back tracking.
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);
        helper(nums, new ArrayList<Integer>(), new boolean[nums.length], res);
        return res;
    }
    private void helper(int[] nums, List<Integer> temp, boolean[] used, List<List<Integer>> res) {
        if (temp.size() == nums.length) res.add(new ArrayList<>(temp));
        else {
            for (int i = 0; i < nums.length; i++) {
                if (used[i] || (i > 0 && !used[i-1] && nums[i] == nums[i-1])) {
                    continue;
                } else {
                    used[i] = true;
                    temp.add(nums[i]);
                    helper(nums, temp, used, res);
                    temp.remove(temp.size()-1);
                    used[i] = false;
                }
            }
        }
    }
}
阅读 1.2k

推荐阅读
Road to Glory
用户专栏

對酒當歌,人生幾何?譬如朝露,去日苦多。

22 人关注
639 篇文章
专栏主页
目录