LeetCode-Permutations

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].
題意:求出一組數的全排
解題思路:對數字按位依次進行交換。

 void p(vector<int> nums,int n,vector<vector<int>>& ret)
    {
        if(n<nums.size()-1)
        {
                for(int j=n;j<nums.size();++j)
                {
                    vector<int> t=nums;
                    int temp =t[n];
                    t[n]=t[j];
                    t[j]=temp;
                    p(t,n+1,ret);
                }
        }
        else
        {
            ret.push_back(nums);
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {

        vector<vector<int>> ret;
        if(nums.size()<2)
        {
            ret.push_back(nums);
            return ret;
        }
        p(nums,0,ret);
        return ret;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章