其他分享
首页 > 其他分享> > Permutations

Permutations

作者:互联网

Constraint:


    1 <= nums.length <= 6
    -10 <= nums[i] <= 10
    All the integers of nums are unique.

Idea

Search:
if the size of permutation set is eaual to array size, add it to the final results list
For each number in the array in range [0, n):
if nums[i] is not visited, add it to the temp permuation set
repeat the search for other nums recursivly
remove nums[i] from the permutation set, and try the next possible index

Code

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

Similar problem:

These all all backtracking problems and can be solved with similar code structures.

标签:nums,Permutations,results,permutation,visited,array,size
来源: https://www.cnblogs.com/blackraven25/p/15106701.html