46. Permutations - Medium

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

 

backtracking

为了防止值重复,用visited数组标记该元素在每一层递归的时候是否被访问过,注意递归到最底层pop元素回到上层的时候,要把此元素的visited状态改成false

time: O(n! * n), space: O(n)

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        boolean[] visited = new boolean[nums.length];
        backtracking(nums, 0, visited, new ArrayList<>(), res);
        return res;
    }
    
    private void backtracking(int[] nums, int idx, boolean[] visited, List<Integer> tmp, List<List<Integer>> res) {
        if(tmp.size() == nums.length) res.add(new ArrayList<>(tmp));
        
        for(int i = 0; i < nums.length; i++) {
            if(visited[i]) continue;
            visited[i] = true;
            tmp.add(nums[i]);
            backtracking(nums, i + 1, visited, tmp, res);
            tmp.remove(tmp.size() - 1);
            visited[i] = false;
        }
    }
}

 

posted @ 2018-12-06 16:56  fatttcat  阅读(106)  评论(0编辑  收藏  举报