码迷,mamicode.com
首页 > 其他好文 > 详细

46. Permutations (Recursion, DP)

时间:2015-10-05 08:12:19      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

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

思路:遍历数组,对于该字母,它可选择与它之后的字母交换或者是不交换=>带回溯的递归

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {
        result.clear();  
        dfs(num,0);
        return result;
        
    }
    void dfs(vector<int> num, int depth)
    {
        if(depth == num.size()-1)
        {
            result.push_back(num);
            return;
        }
        dfs(num,depth+1);
        int temp = num[depth];
        for(int i = depth+1;i< num.size(); i++)
        {
            num[depth] = num[i];
            num[i] = temp;
            dfs(num,depth+1);
            num[i] = num[depth];
            num[depth] = temp;
        }
    }
    
private:
    vector<vector<int> >  result;
};

 

46. Permutations (Recursion, DP)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4855304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!