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