Permutation II Time Limit Exceeded


  • 1
    L

    Hi, I am kind of new in Java.
    I pass my C++ code in the problem, and try to use the same logic in Java code as followed,
    but get a time limit exceeded error.
    I've been tried and error a long time, but still can not figure out why.
    It would be great if someone can point out my blind spot!

    
    public class Solution {
    	public void permute(Stack<Integer> head, LinkedList<Integer> others, List<List<Integer>> perms)
    	{
    		if (others.isEmpty())
    		{
    			perms.add((Stack<Integer>)head.clone());
    			return;
    		}
    		Set<Integer> used = new TreeSet<Integer>();
    		Object[] snapshot = others.toArray();
    		for (Object obj : snapshot)
    		{
    		    Integer i = (Integer)obj;
    			if (used.contains(i))
    				continue;
    			head.push(i);
    			others.remove(i);
    			permute(head, others, perms);
    			others.add(i);
    			head.pop();
    		}
    	}
    	public List<List<Integer>> permuteUnique(int[] num) {
    		List<List<Integer>> perms = new LinkedList<List<Integer>>();
    		Stack<Integer> head = new Stack<Integer>();
    		LinkedList<Integer> others = new LinkedList<Integer>();
    		for (int i : num)
    		{
    			others.add(new Integer(i));
    		}
    		permute(head, others, perms);
    		return perms;
        }
    }
    

  • 0
    L

    Never mind, I've found the root cause.
    It's a bug in my code. Just add a line: used.add(i); and it all works.
    However, I still wonder why the system response a time limit exceeded instead of some more specific reason such as wrong answer...


Log in to reply
 

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