46. Permutations - example

元素 unique, 不允許重複使用

但數字可能會在前面出現, 所以需要 used 限制使用過的, 不能靠 nature order, i = start 來限制用過的

use list.contains => O(n)

time: O(n!*n*n) or just O(n!)

space: O(n!*n)

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) return res;
        helper(res, new ArrayList<>(), nums);
        return res;
        
    }
    //  1.    2.    3
    // 2. 3  1. 3
    private void helper(List<List<Integer>>res , List<Integer> list, int[] nums) {
        if (list.size() == nums.length) {
            res.add(new ArrayList<>(list));
        }
        for (int i = 0; i < nums.length; i++) {
            if (list.contains(nums[i])) {
                continue;
            }
            list.add(nums[i]);
            helper(res, list, nums);
            list.remove(list.size()-1);
        }
    }
}

這就像是 backtracking 的一個一貫作法

            list.add(nums[i]);
            helper(res, list, nums);
            list.remove(list.size()-1);

use used[] , replace list.contains

time: O(n!*n) or O(n!)

space: O(n!*n) or 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;
        boolean used[] = new boolean[nums.length];
        helper(res, new ArrayList<>(), used, nums);
        return res;
        
    }
    //  1.    2.    3
    // 2. 3  1. 3
    private void helper(List<List<Integer>>res , List<Integer> list, boolean used[], int[] nums) {
        if (list.size() == nums.length) {
            res.add(new ArrayList<>(list));
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;
            }
            list.add(nums[i]);
            used[i] = true;
            helper(res, list, used, nums);
            list.remove(list.size()-1);
            used[i] = false;
        }
    }
}

Last updated

Was this helpful?