46 permutation

class Solution {
    public List> permute(int[] nums) {
        List> ans = new ArrayList>();
        helper(nums, 0, ans, new ArrayList());
        return ans;
    }
    private void helper(int[] nums, int idx, List> ans, ArrayList path){
        if(idx == nums.length) {
            ans.add(new ArrayList(path));
            return;
        }
        for(int i = idx; i < nums.length; i++){
            path.add(nums[i]);
            swap(nums, i, idx);
            helper(nums, idx+1, ans, path);
            swap(nums, i, idx);
            path.remove(path.size()-1);
        }
        return;
    }
    
    private void swap(int[] nums, int a, int b){
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }
}

你可能感兴趣的:(46 permutation)