Permutations(46)

46— Permutations

Given a collection of distinct integers, return all possible permutations.

Example 1:

Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

C++代码:
class Solution{
public:
  vector<vector<int> > permute(vector<int> &v){
    vector<vector<int> > result;
    helper(result,v,0);
    return result;
  }
private:
  void helper(vector<vector<int> > &result , vector<int> &v,int start) {
    if(start == v.size()) {
      result.push_back(v);
      return;
    } else {
      for (int i = start; i <v.size() ;i++) {
        swap(v[i],v[start]);
        helper(result,v,start + 1);
        swap(v[i],v[start]); // 即当有一个全排列输出的时候, 交换的位置要恢复
      }
    }
  }
};
Complexity Analysis:

Time complexity : O(n!). T ( n ) = n ∗ T ( n − 1 ) + c n T(n) = n*T(n-1) +cn T(n)=nT(n1)+cn

思路:
  • 递归的思想
  • 求n个数的全排列”, 相当于第一个位置与其他位置交换, 然后对每一个交换的结果求n-1个数的全排列,

例如求“1234”的全排列,

  • 当第一个数与第一个数交换时,相当于求“234”的全排列的;
  • 当第一个数与第二个数交换时,相当于求“134”的全排列;
  • 当第一个数与第三个数交换时,相当于求“214”的全排列;
  • 当第一个数与第四个数交换时,相当于求“231”的全排列;

依次递归, 递归的出口条件是求一个数的全排列,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值