Permutations

Q:

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].

A:

额,其实就是全排列,但是是在没有重复数字的情况下,A[i, j](表示数组A中第i个元素到第j个元素的子数组)的全排列其实就是将i依次与i + 1到j的所有数字互换,然后再与A[i + 1, j]的全排列组合的结果。swap之后记得要swap回来。就这样。

没有编译错误并且一次通过的概率提高了。说明做一些小题还是有提高的。

不过有非递归的做法么。

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return permuteInternal(num, num.size() - 1);
    }
private:
    vector<vector<int> > permuteInternal(vector<int> &num, int end) {
        vector<vector<int> > results;
        vector<int> result;
        if (end < 0) return results;
        if (end == 0) {
            result.push_back(num[end]);
            results.push_back(result);
            return results;
        }
        for (int i = 0; i <= end; ++i) {
            swap(num[end], num[i]);
            vector<vector<int> > part_results = 
                permuteInternal(num, end - 1);
            for (int j = 0; j < part_results.size(); ++j) {
                part_results[j].push_back(num[end]);
                results.push_back(part_results[j]);
            }
            swap(num[end], num[i]);
        }
        return results;
    }
};

 

posted @ 2013-06-16 17:39  dmthinker  阅读(108)  评论(0)    收藏  举报