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

  • 0

    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){
        	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!!!
        	for(int i=0;i<avai.size();i++){
        		int rem = avai.remove(i);
        		DFSperm(avai, temp, res);
        		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.