LeetCode- permutations

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3]have the following permutations:
[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2], and[3,2,1].

import java.util.*;
 
public class Solution {
    public ArrayList> permute(int[] num) {
        ArrayList> retList = new ArrayList>();
        if (num == null || num.length == 0)
            return retList;
        ArrayList list = new ArrayList();
        boolean[] visited = new boolean[num.length];
        dfs(num, visited, list, retList);
        return retList;
    }
    private void dfs(int[] nums, boolean[] visited, ArrayList list, ArrayList> retList) {
        if (list.size() == nums.length) {
            retList.add(new ArrayList(list));
        } else {
            for (int i = 0; i < nums.length; i++) {
                if (!visited[i]) {
                    visited[i] = true;
                    list.add(nums[i]);
                    dfs(nums, visited, list, retList);
                    list.remove(list.size() - 1);
                    visited[i] = false;
                }
            }
        }
    }
     
}

 

你可能感兴趣的:(LeetCode,LeetCode)