Time Limit Exceeded!! how to improve


  • 0
    X
    public class Solution {
    public List<List<Integer>> permuteUnique(int[] num) {
         List<List<Integer>> result =new ArrayList<List<Integer>>();
        int[] use = new int[num.length];
        permuteBackTrace(use,result,new ArrayList<Integer>(),num,0);
        return result;
    }
    
    public static void permuteBackTrace(int[] use, List<List<Integer>> result, List<Integer> temp, int[] num, int level){
        int length = num.length;
        if(level == length && !result.contains(new ArrayList<Integer>(temp))){
            result.add(new ArrayList<Integer>(temp));
            return;
        }else {
            for(int i = 0; i<length; i++){
                if(use[i] == 0){
                    temp.add(num[i]);
                    use[i] = 1;
                    permuteBackTrace(use, result, temp, num, level + 1);
                    use[i] = 0;
                    temp.remove(temp.size() - 1);
                }
            }
        }
    }
    

    }


  • 1
    H

    maintain a separate HashSet to check duplicates instead of using the List to be returned.


Log in to reply
 

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