Permutations @ LeetCode

Source: Internet
Author: User

Package Level3; import java. util. arrayList;/*** Permutations ** Given a collection of numbers, return all possible permutations. for example, [, 3] have the following permutations: [, 3], [, 2], [, 3], [, 1], [, 1, 2], and [3, 2, 1]. **/public class S46 {public static void main (String [] args) {int [] S = {1, 2, 3}; System. out. println (permute (S);} public static ArrayList <Integ Er> permute (int [] S) {ArrayList <Integer> ret = new ArrayList <Integer> (); arrayList <Integer> list = new ArrayList <Integer> (); rec (S, ret, list); return ret;} public static void rec (int [] S, arrayList <Integer> ret, ArrayList <Integer> list) {// when the array length is 0, add the ret if (S. length = 0) {ret. add (new ArrayList <Integer> (list); // You must create an ArrayList Based on the field and add it to ret! Return;} // traverse each number in the array as the first element for (int I = 0; I <S. length; I ++) {// construct a new sub-array to recursion int [] sub = new int [S. length-1]; System. arraycopy (S, 0, sub, 0, I); System. arraycopy (S, I + 1, sub, I, S. length-i-1); // System. out. println (Arrays. toString (sub); list. add (S [I]); rec (sub, ret, list); list. remove (list. size ()-1); // restore site }}}

 

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.