[leetcode]Permutations

有是一道组合排列题目。继续用DFS。不过这次在LeetCode网页里直接写,更接近面试的纸写。

public class Solution {

    public ArrayList<ArrayList<Integer>> permute(int[] num) {

        // Start typing your Java solution below

        // DO NOT write main() function

        ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();

        int len = num.length;

        

        if (len == 0) return ans;

        

        boolean[] vis = new boolean[len];

        int[] kase = new int[len];

        

        

        dfs(ans, 0, len, num, kase, vis);

        

        return ans;

        

    }

    

    public void dfs(ArrayList<ArrayList<Integer>> ans, int k, int n, int[] num, int[] kase, boolean[] vis) {

        if (k == n) {

            ArrayList<Integer> arr = new ArrayList<Integer>();

            for (int i = 0; i < kase.length; i++) {

                arr.add(kase[i]);

            }

            ans.add(arr);

            return;

        }

        else {

            for (int i = 0; i < num.length; i++) {

                if (!vis[i]) {

                    kase[k] = num[i];

                    vis[i] = true;

                    dfs(ans, k+1, n, num, kase, vis);

                    vis[i] = false;

                }

            }

        }

    }

}

  

你可能感兴趣的:(LeetCode)