Permutation Sequence(LeetCode)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014485485/article/details/80955049

The set [1,2,3,...,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note:

  • Given n will be between 1 and 9 inclusive.
  • Given k will be between 1 and n! inclusive.

Example 1:

Input: n = 3, k = 3
Output: "213"

Example 2:

Input: n = 4, k = 9
Output: "2314"

给定一个数n,求1~n这组数按顺序排的第k个排列数。要求返回string类型

思路:1.求得全排列,返回第k个——这个时间复杂度太高,过不了

class Solution {
public:
	string getPermutation(int n, int k) {
		vector<string> ans;
		string cur;
		vector<bool> mark(n, false);
		dfs(n,k, 0, ans, cur, mark);
		return ans[k-1];
	}

	void dfs(int n, int k, int num, vector<string>& ans, string& cur, vector<bool>& mark) {
		if (num == n) {//排完了,存入
			ans.push_back(cur);
			if (ans.size() == k)
				return;
		}
		for (int i = 1; i <= n; i++) {
			if (mark[i] == false) {//标记信号,这个数在不在cur里,不在,就存入
				cur.append(to_string(i));
				mark[i] = true;
				dfs(n,k, num + 1, ans, cur, mark);
				cur.erase(cur.end()-1);//回溯
				mark[i] = false;
			}
		}
	}
};

2.我们可以求得n个数的全排列个数有多少(n!),根据这个个数简化计算。举个例子

n: 1 2 3 4

k=10;

 1 2 3 个数的全排列个数:1 2 6

换成索引,k按10-1=9算,在1 2 3 4中找第9个排列

9/6=1;索引为1,所以要求的排列第一个数就是2

9%6=3;在1 3 4中找第3个排列


3/2=1;索引为1,所以要求的排列第二个数就是3

3%2=1;在1 4中找第1个排列


1/1=0;索引为0,所以要求的排列第三个数就是1

1%1=0;在4中找第0个排列


最后只剩一个数,全排列即为其本身,可以写成:

0/1=0;索引为0,所以要求的排列第四个数就是4

0%1=0;

结束

class Solution {
public:
	string getPermutation(int n, int k) {
		vector<int> res;
		for (int i = 1; i <= n; i++) {
			res.push_back(i);
		}
		vector<int> fact(n,0);
		fact[0] = 1;
		for (int i = 1; i < n; i++) {//算阶乘
			fact[i] = i*fact[i - 1];
		}
		k = k - 1;//0到k-1
		string str;
		for (int i = n; i > 0; i--) {
			int index = k / fact[i - 1];
			k = k%fact[i - 1];
			str.append(to_string(res[index]));
			vector<int>::iterator iter = res.begin() + index;
			res.erase(iter);
		}
		return str;
	}
};

猜你喜欢

转载自blog.csdn.net/u014485485/article/details/80955049