[leetCode]46. 全排列

在这里插入图片描述

回溯

class Solution {

    private List<List<Integer>> ans = new LinkedList<>();

    public List<List<Integer>> permute(int[] nums) {
        backTrace(nums, 0);
        return ans;
    }

    private void backTrace(int[] nums, int begin) {
        if (begin == nums.length) {
            List<Integer> one = new LinkedList<>();
            for (int num : nums) {
                one.add(num);
            }
            ans.add(one);
        }
        for (int i = begin; i < nums.length; i++) {
            exch(nums, i, begin);
            backTrace(nums, begin + 1);
            exch(nums, i, begin);
        }
    }

    private void exch(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
posted @ 2020-10-06 12:25  消灭猕猴桃  阅读(56)  评论(0编辑  收藏  举报