46

回溯法

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(res, nums, new ArrayList<Integer>());
        return res;
    }
    private void backtrack(List<List<Integer>> res, int[] nums, ArrayList<Integer> temp) {
        if (temp.size() == nums.length) {
            res.add(new ArrayList<>(temp));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (temp.contains(nums[i])) continue;
            temp.add(nums[i]);
            backtrack(res, nums, temp);
            temp.remove(temp.size() - 1);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/zhaijiayu/p/11526892.html
46
今日推荐