[Algorithm] C++ 全排列

56 阅读1分钟

1. 每日一题

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

输入: nums = [1,2,3]
输出: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
void backtrack(std::vector<std::vector<int> > &res, std::vector<int> &output,
               int first, int len) {
  // 所有数都填完了
  if (first == len - 1 ) {
    res.push_back(output);
    return;
  }
  for (int i = first; i < len; ++i) {
    // 动态维护数组
    std::swap(output[i], output[first]);
    // 继续递归填下一个数
    backtrack(res, output, first + 1, len);
    // 撤销操作
    std::swap(output[i], output[first]);
  }
}

std::vector<std::vector<int> > permute(std::vector<int> &nums) {
  std::vector<std::vector<int> > res;
  backtrack(res, nums, 0, (int)nums.size());
  return res;
}