full permutation

bool _CanSwap(char* str, int start, int end) {
  while (start < end) {
    if (str[start++] == str[end]) {
      return false;
    }
  }
  return true;
}

void _Permutation(char* str, int start, int end) {
  if (start == end) {
    std::cout << str << std::endl;
  } else {
    for (int i = start; i <= end && _CanSwap(str, start, i); i++) {
      std::swap(str[start], str[i]);
      _Permutation(str, start + 1, end);
      std::swap(str[start], str[i]);
    }
  }
}

void PermutationWithRec(char* str) {
  _Permutation(str, 0, strlen(str) - 1);
}

bool _PermutationNoRec(char* str) {
  int len = strlen(str);
  for (int i = len - 2; i >= 0; --i) {
    if (str[i] < str[i + 1]) {
      for (int j = len - 1; j > i; --j) {
        if (str[j] > str[i]) {
          std::swap(str[i], str[j]);
          _strrev(str + i + 1);
          return true;
        }
      }
    }
  }
  _strrev(str);
  return false;
}

void PermutationNoRec(char* str) {
  std::sort(str, str + strlen(str));
  do {
    std::cout << str << std::endl;
  } while (_PermutationNoRec(str));
}

 

posted @ 2013-10-31 23:06  avexer  阅读(241)  评论(0编辑  收藏  举报