LeetCode: Permutations
2012-12-05 14:50
309 查看
Given a collection of numbers, return all possible permutations.
For example,
固定第一位,然后算后面的全排列。然后再将第一位固定为其他的值。
Crack Code Interview上给的方法是先固定一个值,找出剩下的值的全排列,然后在把这个固定的值插入到不同的位置,得到新的全排列。
感觉写起来不如这个直观。
For example,
[1,2,3]have the following permutations:
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2], and
[3,2,1].
固定第一位,然后算后面的全排列。然后再将第一位固定为其他的值。
Crack Code Interview上给的方法是先固定一个值,找出剩下的值的全排列,然后在把这个固定的值插入到不同的位置,得到新的全排列。
感觉写起来不如这个直观。
class Solution { public: vector<vector<int> > permute(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > res; vector<int> rcd; subPermute(res, num, rcd); return res; } void subPermute(vector<vector<int> > &res, vector<int> &num, vector<int> &rcd){ if(num.size() == 0){ res.push_back(rcd); return; } for(int i = 0; i < num.size(); ++i){ vector<int> temp = num; rcd.push_back(temp[i]); for(int j = i; j < num.size() -1 ;++j){ temp[j] = temp[j+1]; } temp.pop_back(); subPermute(res, temp, rcd); rcd.pop_back(); } } };
相关文章推荐
- leetcode-Permutations
- LeetCode46_Permutations
- [leetcode] Permutations
- [LeetCode] Permutations 解题报告
- LeetCode 46 Permutations
- 【leetcode】【46】Permutations
- [LeetCode 题解]: Permutations
- [Leetcode]Permutations
- [LeetCode] Permutations
- LeetCode(46): Permutations (C++)
- LeetCode Permutations II
- [LeetCode]Permutations,解题报告
- [leetcode]Permutations
- [leetcode]Permutations
- leetcode 之 Permutations 解题思路
- Permutations - LeetCode
- leetcode---Permutations
- leetcode---permutations-ii---dfs
- LeetCode 46:Permutations
- LeetCode 046 Permutations