My solution based on Next Permutation.


  • 2
    K

    My solution is based on the solution of Next Permutation (https://oj.leetcode.com/problems/next-permutation/). If you solve the Next Permutation problem, you can solve this problem very easily.

    class Solution {
    public:
        vector<vector<int> > permute(vector<int> &num) {
            vector<vector<int> > result;
            vector<int> num1;
            num1 = nextPermutation(num);
            result.push_back(num1);
            while(num1!=num)
            {
                num1 = nextPermutation(num1);
                result.push_back(num1);
            }
            return result;
        }
        
        vector<int> nextPermutation(vector<int> num) {
           int N = num.size();
            for(int i=N-1;i!=0;i--)
            {
                if(num[i-1]<num[i])
                {
                    for(int j =N-1;j!=i-1;j--)
                    {
                        if(num[j]>num[i-1])
                        {
                            num[j]^=num[i-1];
                            num[i-1]^=num[j];
                            num[j]^=num[i-1];
                            reverse(num.begin()+i,num.end());
                            return num;
                        }
                    }
                }
            }
            reverse(num.begin(),num.end());
            return num;  
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.