leetcode-46 Permutations

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38340127/article/details/89873717

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

实现全排序

方法一:

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        permute(nums,new ArrayList<>(),res);
        return res;
    }
    
    public void permute(int[] nums, List<Integer> now, List<List<Integer>> res) {
        if (now.size() == nums.length && !now.isEmpty()) {
            res.add(new ArrayList<>(now));
        }
        for (int index = 0; index < nums.length; index++) {
            if (!now.contains(nums[index])) {
                now.add(nums[index]);
                permute(nums, now, res);
                now.remove(now.size()-1);
            }
        }

    }

方法二:根据字典排序 每次找出下一个值 直到没有。具体实现参考47

猜你喜欢

转载自blog.csdn.net/qq_38340127/article/details/89873717