> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/dfs-and-bfs/dfs/tips/46.-permutations-example.md).

# 46. Permutations - example

![](/files/-MdRMkfT107hvsr5EQM2)

元素 unique, 不允許重複使用

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

## use list.contains => O(n)

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

space: O(n!\*n)

```java
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 的一個一貫作法

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

![](/files/-MdRNak95Bd74OSZotV1)

## use used\[] , replace list.contains

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

space: O(n!\*n) or O(n!)

```java
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;
        }
    }
}
```
