6 ms and 20 line Java clean backtracking solution.


  • 0
    T
    public class Solution {
        List<List<Integer>> ans = new LinkedList();
        LinkedList<Integer> comb = new LinkedList();
        public List<List<Integer>> permute(int[] nums) {
            int count[] = new int[nums.length];
            backTrack(nums,0,count);
            return ans;
        }
        private void backTrack(int[] nums, int level, int[] c){
            if(comb.size()>=nums.length){
                LinkedList<Integer> t = (LinkedList<Integer>) comb.clone();
                ans.add(t);
                return;
            }
            for(int i=0;i<nums.length;i++){
                if(c[i]==0){
                c[i]++;
                comb.add(nums[i]);
                backTrack(nums,i+1,c);
                c[i]--;
                comb.remove(comb.size()-1);
                }
            }
        }
    }
    

Log in to reply
 

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