zoukankan      html  css  js  c++  java
  • [Leetcode 53] 46 Permutations

    Problem:

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

    Analysis:

    It's a backtracking problem. In order to make sure that we don't access the same element multiple times, we use an extra tag array to keep the access information. Only those with tag value equals 0 will be chose as candidates.

    Code:

     1 class Solution {
     2 public:
     3     vector<vector<int> > res;
     4 
     5     vector<vector<int> > permute(vector<int> &num) {
     6         // Start typing your C/C++ solution below
     7         // DO NOT write int main() function
     8         if (num.size() == 0) return res;
     9         
    10         res.clear();
    11         vector<int> r;
    12         vector<int> tag(num.size(), 0);
    13         bc(r, tag, num);
    14         
    15         return res;
    16     }
    17     
    18     void bc(vector<int> path, vector<int> &tag, vector<int> &num) {
    19         if (path.size() == num.size()) {
    20             res.push_back(path);
    21             return ;
    22         }
    23         
    24         for (int i=0; i<num.size(); i++) {
    25             if (tag[i] == 0) {
    26                 path.push_back(num[i]);
    27                 tag[i] = 1;
    28                 bc(path, tag, num);
    29                 tag[i] = 0;
    30                 path.pop_back();
    31             }   
    32         }
    33         
    34         return ;
    35     }
    36 };
    View Code
  • 相关阅读:
    ajax长轮询实现即时聊天室
    node.js 通过post上传图片并显示
    Java集合类详解
    多行子查询
    Oracle中查看用户下面所有表的语句
    关于Oracle的create
    Oracle数据库学习
    oracle数据库
    js 中 undefined、NaN、null
    学习数据库SQL语句2
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099599.html
Copyright © 2011-2022 走看看