1. 程式人生 > >回溯Leetcode 46 Permutations

回溯Leetcode 46 Permutations

Leetcode 46

Permutations

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; } };