leetcode Permutations

题目链接

思路:
递归回溯。典型应用

public class Solution {
    int n;
    List<List<Integer>>  result;
    List<Integer> temp;
    boolean  isUsed[];
    int[]nums;

    public List<List<Integer>> permute(int[] nums) {
        n=nums.length;
        isUsed=new boolean[n];
        temp=new LinkedList<Integer>();
        result=new LinkedList<List<Integer>>();
        this.nums=nums;
        help(0);
        return result;
    }

    public void help(int step)
    {
        if(step==n)
        {
            result.add(new LinkedList<Integer>(temp));
            return;
        }


        for(int i= 0;i<n;i++)
        {
            if(!isUsed[i])
            {
                isUsed[i]=true;
                temp.add(nums[i]);
                help(step+1);
                isUsed[i]=false;
                temp.remove(temp.size()-1);
            }
        }

    }
}

你可能感兴趣的:(leetcode Permutations)