LeetCode 46. Permutations(同47,只是不包含重复数字)

来源:互联网 发布:外国人评价三体 知乎 编辑:程序博客网 时间:2024/06/07 17:16

Given a collection of distinct 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],  [3,2,1]]

public class Solution {    public List<List<Integer>> permute(int[] nums) {        if(nums==null||nums.length==0)         return null;        int len = nums.length;        int[] isUsed = new int[len];        List<List<Integer>> result = new ArrayList<List<Integer>>();        List<Integer> store = new ArrayList<Integer>();        dfs(result,isUsed,store,nums);        return result;    }        public void dfs(List<List<Integer>> result, int[] isUsed, List<Integer> store, int[] nums) {    if(store.size()==nums.length){    result.add(new ArrayList<>(store));    return;    }    for(int i=0;i<nums.length;i++){    if(isUsed[i]==1)     continue;    store.add(nums[i]);    isUsed[i]=1;    dfs(result,isUsed,store,nums);    isUsed[i]=0;    store.remove(store.size()-1);    }}}


0 0
原创粉丝点击