回溯Leetcode 46 Permutations
阿新 • • 發佈:2018-12-28
Leetcode 46
Permutations
- Problem Description:
經典回溯問題:無重複數字的全排列
具體的題目資訊:
https://leetcode.com/problems/permutations/description/ - Example:
- Solution:
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int >> res;
if (nums.size() == 0) return res;
permutation(nums, 0, res);
return res;
}
void permutation(vector<int>& nums, int i, vector<vector<int>>& res) {
if (i == nums.size()-1) {
vector<int> t;
for (int j = 0; j < nums.size(); j++) {
t.push_back(nums[j]);
}
res.push_back(t);
return;
} else {
for (int j = i; j < nums.size(); j++) {
swap(nums, i, j);
permutation(nums, i+1, res);
swap(nums, j, i);
}
}
}
void swap(vector<int>& nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
};