美文网首页
46 permutation

46 permutation

作者: Fei_JOB | 来源:发表于2017-10-23 12:42 被阅读0次
class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        helper(nums, 0, ans, new ArrayList<Integer>());
        return ans;
    }
    private void helper(int[] nums, int idx, List<List<Integer>> ans, ArrayList<Integer> path){
        if(idx == nums.length) {
            ans.add(new ArrayList<Integer>(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

      本文链接:https://www.haomeiwen.com/subject/twzouxtx.html