Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

Any suggestion for my code[ nice in Eclipse but time exceed limit in leetcode]

0 votes
53 views

Any suggestion for my code?

The algorithm is that I take out the last element of the array and put the rest into the permuteUnique for every recursive. The current result will be depend on the last result by insert the last element into each position of the last results.

public class Solution {
    public static ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {  
        Arrays.sort(num);
        ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> cur = new ArrayList<Integer>();
        if (num.length == 1){
            cur.add(num[0]);
            results.add(cur);
            return results;
        }

        /*get the last element, namely, the one which use to insert into the last result**/
        int lastElement = num[num.length-1];
        int[] subSet = new int[num.length-1];

        /*get the rest and put it into recursive**/
        System.arraycopy (num, 0, subSet, 0, num.length-1);
        results = combine (lastElement, permuteUnique(subSet), results);
        return results;
    }

    private static ArrayList<ArrayList<Integer>> combine (int insertor, ArrayList<ArrayList<Integer>> subSet, ArrayList<ArrayList<Integer>> results){
        /* get every ArrayList and insert the element into each possible position **/
        for (int i = 0; i < subSet.size(); i ++){
            for (int j = 0; j < subSet.get(i).size()+1; j ++){
                ArrayList<Integer> subTemp = new ArrayList<Integer>();
                subTemp = (ArrayList<Integer>) subSet.get(i).clone();
                subTemp.add(j,insertor);
                /* check duplicate **/
                if (! results.contains(subTemp)){
                    results.add(subTemp);
                }
            }
        }
        return results;
    }
}
asked Jan 4 in Permutations II by buffxz (140 points)
edited Jan 4 by buffxz

Could you please update your post to explain your algorithm and add comments in code?

OK done. Thanks!

Please log in or register to answer this question.


...