47.Permutations 1&2

Source: Internet
Author: User

1.Given A collection of numbers, return all possible permutations.

For example,
[1,2,3]The following permutations:
[1,2,3],,,,, [1,3,2] [2,1,3] [2,3,1] [3,1,2] and [3,2,1] .

2.

Given A collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2]The following unique permutations:
[1,1,2], [1,2,1] , and [2,1,1] .

Solution:dfs

1 2 3

12 13 21 23 32 31

123 132 213 231 321 312

 PackageLeetcode2;ImportJava.util.*; Public classpermutations { Public StaticArraylist<arraylist<integer>> Permute (int[] num) {ArrayList<ArrayList<Integer>> res=NewArraylist<arraylist<integer>>(); ArrayList<Integer> mem =NewArraylist<integer>(); intDeep=0; intLength=num.length; Booleanvisit[]=New Boolean[length];         DFS (RES,MEM,DEEP,NUM,VISIT,LENGTH); returnRes; }          Public Static voidDFS (arraylist<arraylist<integer>>Res, ArrayList<Integer> Mem,intDeepint[] num,Boolean[] Visit,intl) {//TODO auto-generated Method Stub        if(deep==l) {            if(!res.contains (NewArraylist<integer>(MEM))) {Res.add (NewArraylist<integer>(MEM)); }            return; }        if(deep<l) {             for(inti=0;i<l;i++){                if(i>0 && num[i-1] = = Num[i] &&!visit[i-1])                 Continue; if(!Visit[i])                {Mem.add (num[i]); Visit[i]=true; DFS (Res,mem,deep+1, num,visit,l); if(Mem.size () >0) {Mem.remove (mem.size ()-1); Visit[i]=false; }                }            }        }        if(deep>num.length)return; }     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub     int[] a={1,2,3};    System.out.print (Permute (a)); }}

47.Permutations 1&2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.