LeetCode:Permutation Sequence
2013-08-03 11:38
253 查看
我首先用vector进行保存,全部便利一遍,结果TLE了,不过遍历代码还是有参考价值的。
最后参考如何按从小到大遍历直到k为止
class Solution { public: vector<string> result; void search(int index,int max,int* A) { if(index==max) { string s; s = ""; for(int i =1;i<=max ;i++) s+=(char)(A[i]+'0');//string如何加一个char字符 result.push_back(s); return; } for(int i = index;i<=max;i++) { swap(A[i],A[index]); search(index+1,max,A); swap(A[i],A[index]); } } string getPermutation(int n, int k) { // Start typing your C/C++ solution below // DO NOT write int main() function result.clear(); int*A = new int[n+1]; for(int i = 1;i<=n;i++) A[i] = i; search(1,n,A); sort(result.begin(),result.end());//如何对vector进行排序 return result[k-1]; } };
最后参考如何按从小到大遍历直到k为止
class Solution { private: string result; int A[10]; public: bool search(int index,int n,int&k,bool* used) { if(index==n+1) { k--; if(k==0) { result = ""; for(int i =1;i<=n;i++) result+=(char)(A[i]+'0'); return true; } return false; } for(int i =1;i<=n;i++) { if(used[i]==false) { A[index] = i; used[i] = true; if(search(index+1,n,k,used))return true; used[i] =false; } } } string getPermutation(int n, int k) { // Start typing your C/C++ solution below // DO NOT write int main() function bool* used = new bool[n+1]; if(k==0) return ""; for(int i =1;i<=n;i++) used[i]=false; result =""; search(1,n,k,used); delete[] used; return result; } };
相关文章推荐
- [LeetCode] Permutation Sequence, Solution
- 4.30 leetcode -30 permutation-sequence
- LeetCode OJ Permutation Sequence
- 【leetcode 排列组合问题】Next Permutation | Permutations | Permutations II | Permutation Sequence
- Permutation Sequence [leetcode]
- Leetcode_permutation-sequence(c++ and python version)
- [leetcode]Permutation Sequence
- LeetCode Permutation Sequence
- [leetcode]Permutation Sequence @ Python
- 【Leetcode】【python】Permutation Sequence
- LeetCode 60 - Permutation Sequence
- leetcode Permutation Sequence
- Permutation Sequence @leetcode
- * Permutation Sequence - Leetcode
- Permutation Sequence leetcode java
- [LeetCode]Permutation Sequence
- leetcode-60-Permutation Sequence
- Leetcode153: Permutation Sequence
- leetcode Permutation Sequence
- LeetCode Permutation Sequence