java 枚举 二进制_LeetCode 46. Permutations C++/Java/Python3 枚举每个位置上放哪个数 二进制优化...

算法

枚举每个位置上放哪个数 二进制优化

时间复杂度: O(n!)

空间复杂度: O(n)

没有二进制优化的时间复杂度: O(n^n)

常见时间复杂度从小到大排序(一般情况):

O(1) < O(log(n)) < O(n) < O(n*log(n)) < O(n^2) < O(n^3) < O(n) < O(2^n) < O(n!) < O(n^n)

因为这道题求全排列,所以时间复杂度最少是O(n!)

C++代码

class Solution {

public:

static vector> permute(const vector &nums) {

vector> res;

if (nums.empty()) {

return res;

}

const int n = static_cast(nums.size());

vector path(n);

permuteDfs(nums, 0, path, 0, res);

return res;

}

private:

static void permuteDfs(const vector &nums, const int numIndexVisited, //

vector &path, const int pathIndex, vector> &res) {

const int n = static_cast(path.size());

if (pathIndex == n) {

res.push_back(path);

return;

}

// 取所有的空位

int numIndexVisitedBis = (~numIndexVisited) & ((1 << n) - 1);

while (numIndexVisitedBis) {

// 取最低位的1

const int numIndexVisitedBit = numIndexVisitedBis & (-numIndexVisitedBis);

const int bit1 = numIndexVisitedBit - 1;

const int numIndex = bitCountArr[(bit1 >> 24) & 0xff] + bitCountArr[(bit1 >> 16) & 0xff] +

bitCountArr[(bit1 >> 8) & 0xff] + bitCountArr[bit1 & 0xff];

path[pathIndex] = nums[numIndex];

permuteDfs(nums, numIndexVisited | numIndexVisitedBit, path, pathIndex + 1, res);

// 清除最低位的1

numIndexVisitedBis &= numIndexVisitedBis - 1;

}

}

static int bitCount(int n) {

int cnt = 0;

for (; n; n &= n - 1) {

++cnt;

}

return cnt;

}

static array staticInitBitCountArr() {

array bitCountArr;

const int n = static_cast(bitCountArr.size());

for (int i = 0; i < n; ++i) {

const int bitCnt = bitCount(i);

bitCountArr[i] = bitCnt;

}

return bitCountArr;

}

static const array bitCountArr;

};

const array Solution::bitCountArr = Solution::staticInitBitCountArr();

Java代码

Python3代码

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值