leetcode46. 全排列(回溯)

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

示例:

输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

代码

class Solution {
    List<List<Integer>> cList=new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {

        per(nums,new ArrayList<>(),new boolean[nums.length]);
        return cList;
    }
    public void per(int[] nums,List<Integer> temp,boolean[] check) {
        if(nums.length==temp.size())//边界
        {

            cList.add(new ArrayList<>(temp));
            return;
        }

        for(int i=0;i<nums.length;i++)//选择
        {
            if(check[i]) continue;
            temp.add(nums[i]);
            check[i]=true;
            per(nums, temp, check);
            check[i]=false;//回溯
            temp.remove(temp.size()-1);

        }

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44560620/article/details/107761153
今日推荐