Listing all permutations of a string/integer

后端 未结 29 2760
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 00:44

A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.

Is there

29条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 01:16

    void permute (char *str, int ptr) {
      int i, len;
      len = strlen(str);
      if (ptr == len) {
        printf ("%s\n", str);
        return;
      }
    
      for (i = ptr ; i < len ; i++) {
        swap (&str[ptr], &str[i]);
        permute (str, ptr + 1);
        swap (&str[ptr], &str[i]);
      }
    }
    

    You can write your swap function to swap characters.
    This is to be called as permute(string, 0);

提交回复
热议问题