JAVA AC recursive solution


  • 0
    H
    public List<List<Integer>> permute(int[] nums) {
    	List<List<Integer>> wrapList = new ArrayList<>();
    	HashSet<Integer> set = new HashSet<>();
    	for (int i = 0; i < nums.length; i++) {
    		ArrayList<Integer> innerList = new ArrayList<>();
    		set.add(nums[i]);
    		innerList.add(nums[i]);
    		loop(wrapList, set, nums, innerList, 1);
    		set.remove(nums[i]);
    	}
    	return wrapList;
    }
    private void loop(List<List<Integer>> wrapList, HashSet<Integer> set, int[] nums,
    		ArrayList<Integer> innerList, int i){
    	if (i == nums.length) {
    		wrapList.add((List)innerList.clone());
    		return;
    	}
    	for (int j = 0; j < nums.length; j++) {
    		if (set.add(nums[j])) {
    			innerList.add(nums[j]);
    			loop(wrapList, set, nums, innerList, i + 1);
    			set.remove(nums[j]);
    			innerList.remove(i);
    		}
    	}
    }

Log in to reply
 

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