C++ non-recursive solution


  • 0
    X
    class Solution {
    public:
        /**
         * @param nums: A list of integers.
         * @return: A list of permutations.
         */
        vector<vector<int> > permute(vector<int> nums) {
            vector<vector<int> > ret;
            if (nums.size() == 0)
                return ret;
            ret.push_back(nums);
            for (int i = 0; i < nums.size(); i++) {
                int sz = ret.size();
                for (int r = 0; r < sz; r++) {
                    for (int j = i+1; j < nums.size(); j++) {
                        vector<int> u(ret[r]);
                        swap(u[i], u[j]);
                        ret.push_back(u);
                    }
                }
            }
            return ret;
        }
    };
    

Log in to reply
 

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