Short, fast and easy to understand Java solution recursion


  • 0
    S
    class Solution {
        List<List<Integer>> result = new ArrayList<>();
        public List<List<Integer>> permute(int[] nums) {
            permute(nums,nums.length);
            return result;
        }
        
        private void permute(int[] nums, int n) {
            if(n==1) {
                List<Integer> list = new ArrayList<>();
                for(int i=0; i<nums.length; i++) {
                    list.add(nums[i]);
                }
                result.add(list);
                return;
            }
            
            for(int i=0; i<n; i++) {
                swap(nums, i,n-1);
                permute(nums, n-1);
                swap(nums, i,n-1);
            }
            
        }
        
        private void swap(int[] arr, int i, int j) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.