# 46. Permutations - example

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MdQ3arr8GMe42mLNASO%2F-MdRMkfT107hvsr5EQM2%2Fimage.png?alt=media\&token=21812439-e084-442f-bade-84c2c957e0c8)

元素 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);
```

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MdQ3arr8GMe42mLNASO%2F-MdRNak95Bd74OSZotV1%2Fimage.png?alt=media\&token=257b7a9f-76db-40eb-b43d-1d8e53840aaf)



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