List all the combinations of numbers in an array (recursive)

Source: Internet
Author: User

List all the combinations of numbers in an array, such as 1 and 2, listed as 12,21 ? Code

The idea is to fix the prefix prefix, and then there's the remaining candidate candidate. Select some of the candidates and add them back to the prefix.
For example, fix prefix 1, then add 2, then select 3 from the following 34, then 4. Get 1234. Or choose 4 from the back 34, then 3. Get 1243.

static void Listall (List candidate, String prefix) {
     if (Candidate.isempty ()) {
    System.out.println (prefix);
     } for

    (int i = 0; i < candidate.size (); i++) {
        List temp = new LinkedList (candidate);
        Listall (temp, prefix + temp.remove (i));
    }

The code took advantage of some features, linkedlist delete operations faster, remove returned is the deleted elements
The function's arguments are parsed from the right, and after the remove, the value of the Temp pass is also a container with one less. In this way, the candidate gradually becomes smaller to reach the recursive jump condition. ? Use String to implement

static void Listall (string candidate, string prefix) {
    if (candidate.length () = = 0) {
        System.out.println (prefix) ;
    }

    for (int i = 0; i < candidate.length (); i++) {
        char Prefixchar = Candidate.charat (i);

        Listall (Candidate.replace (Prefixchar + "", ""), prefix + Prefixchar);
    }
? Test
public static void Main (string[] args) throws IOException {
    string[] arrays = new string[] {"1", "2", "3", "4"};
  listall (Arrays.aslist (Arrays), "");
    Listall ("1234", "");
}

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.