60. Permutation Sequence
2016-03-11 23:43
453 查看
The set
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
// Construct the k-th permutation with a list of n numbers
// Idea: group all permutations according to their first number (so n groups, each of
// (n-1)! numbers), find the group where the k-th permutation belongs, remove the common
// first number from the list and append it to the resulting string, and iteratively
// construct the (((k-1)%(n-1)!)+1)-th permutation with the remaining n-1 numbers
[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 (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
string getPermutation(int n, int k) { int total=1, idx, i; vector<char> nums; for(i = 1; i <= n; i++) { nums.push_back(i+'0'); total *= i; } if(k>total || k<1) return ""; string s; s.resize(n); i = 0; while(n) { total /= n; idx = (k-1) / total; s[i++] = nums[idx]; nums.erase(nums.begin()+idx); k = (k-1) % total +1; //can also be k -= group * idx n--; } return s; }
// Construct the k-th permutation with a list of n numbers
// Idea: group all permutations according to their first number (so n groups, each of
// (n-1)! numbers), find the group where the k-th permutation belongs, remove the common
// first number from the list and append it to the resulting string, and iteratively
// construct the (((k-1)%(n-1)!)+1)-th permutation with the remaining n-1 numbers
相关文章推荐
- UIImage 虚线框 可以用作 UITextfield、UIButton 的background,
- NGUI DrawCall优化
- 用UIPickerView来显示省和市
- java continue 语句的应用
- HDFS之SequenceFile和MapFile
- UIPicker city.plist(实例)
- iOS开发基础 :UILabel属性
- UIScroll和UIPickView
- android的ui组件布局提示:android.widget.XXX cannot be cast to android.widget.YYY解决
- iiOS 开发基础:UIImageView属性
- iOS开发基础 :UIButton属性
- String ,Stringbuffer ,StringBuilder;
- Android子线程中更新UI的3种方法
- iOS开发--UIPickerView(选择器控件) 省份和城市的做法
- UINavigationController导航控制器
- 最新OSSIM改装平台DEMO WebUI
- bind 的第三方性能测试工具 queryperf
- UITableView和UICollectionView列表出现重叠问题
- iOS--UIAlertView与UIAlertController和UIAlertAction之间的事儿
- UIPickerView