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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/dfs-and-bfs/dfs/tips/46.-permutations-example.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
