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


  • 1
    B

    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;
        }
    }

  • 0
    S

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


  • 0
    B

    OK done. Thanks!


Log in to reply
 

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