[Leetcode 53] 46 Permutations
2013-05-26 05:58
429 查看
Problem:
Given a collection of numbers, return all possible permutations.
For example,
Analysis:
It's a backtracking problem. In order to make sure that we don't access the same element multiple times, we use an extra tag array to keep the access information. Only those with tag value equals 0 will be chose as candidates.
Code:
View Code
Given a collection of numbers, return all possible permutations.
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].
Analysis:
It's a backtracking problem. In order to make sure that we don't access the same element multiple times, we use an extra tag array to keep the access information. Only those with tag value equals 0 will be chose as candidates.
Code:
class Solution { public: vector<vector<int> > res; vector<vector<int> > permute(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function if (num.size() == 0) return res; res.clear(); vector<int> r; vector<int> tag(num.size(), 0); bc(r, tag, num); return res; } void bc(vector<int> path, vector<int> &tag, vector<int> &num) { if (path.size() == num.size()) { res.push_back(path); return ; } for (int i=0; i<num.size(); i++) { if (tag[i] == 0) { path.push_back(num[i]); tag[i] = 1; bc(path, tag, num); tag[i] = 0; path.pop_back(); } } return ; } };
View Code
相关文章推荐
- leetcode 46 Permutations
- [leetcode 46] Permutations
- LeetCode46 Permutations
- LeetCode_46---Permutations
- LeetCode 46: Permutations
- LeetCode 46 Permutations
- leetcode 46 : Permutations
- LeetCode 46: Permutations
- LeetCode力扣之46_Permutations
- LeetCode-46-Permutations 暴力递归
- 【LEETCODE】46-Permutations
- leetcode 46: permutations
- LeetCode46,47 Permutations, Permutations II
- Leetcode-46: Permutations
- leetcode[46]Permutations
- leetcode——46——Permutations
- Leetcode 46 Permutations
- LeetCode(46)Permutations
- LeetCode- 46/47. Permutations/Permutations || (JAVA) (全排列1,2)
- leetcode46/47-Permutations I/II(全排列问题)