Could you plz tell me why this doesn't work?


  • 0
    Z
    static List<List<Integer>> result = new ArrayList<List<Integer>>();
    public static void permutation(List<Integer> prefix, List<Integer> post) {
    		if (post.size() == 0)
    			result.add(prefix);
    		else {
    			for (int i = 0; i < post.size(); i++) {
    				prefix.add(post.get(i));
    				List<Integer> temp = post;
    				temp.remove(i);
    				permutation(prefix, temp);
    			}
    		}
    	}

  • 1
    Z

    Looks like in the for loop, you are keeping adding new elements into prefix, and pass it to the next iteration without restore its original status.

    For example, when i = 0, you have modified prefix as prefix = prefix.add(post.get(0)). Note that the modified prefix is brought into the next loop, where i = 1. So in this loop you add an element to the modified prefix rather than the original one.


Log in to reply
 

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