Easy to understand Java solution, simple DFS of an implicit tree.


  • 0
    G

    I know some of you have set up a boolean array to make sure the permutation work well. I simply used a "List<Integer> avai" which stores the available numbers. My code is as follows:

    public List<List<Integer>> permute(int[] nums) {
        	List<List<Integer>> res = new ArrayList<>();
        	List<Integer> avai = new ArrayList<>();
        	for(int i:nums){
        		avai.add(i);
        	}
        	List<Integer> temp = new ArrayList<>();
        	DFSperm(avai, temp, res);
        	return res;
        }
        
        private void DFSperm(List<Integer> avai, List<Integer> temp, List<List<Integer>> res) {
        	if(avai.isEmpty()) {
        		res.add(new ArrayList<>(temp));//do not forgot the new again!!!
        		return;
        	}
        	
        	for(int i=0;i<avai.size();i++){
        		int rem = avai.remove(i);
        		temp.add(rem);
        		DFSperm(avai, temp, res);
        		temp.remove(temp.size()-1);
        		avai.add(i, rem); //struggled some time in this place;
        	}
        }

Log in to reply
 

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