标签:style blog color os 使用 io for div cti
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
思路:先对num进行排序,然后直接调用标准库的next_permutation函数求解。
1 class Solution { 2 public: 3 vector<vector<int>> permuteUnique( vector<int> &num ) { 4 vector<vector<int>> permutations; 5 sort( num.begin(), num.end() ); 6 permutations.push_back( num ); 7 while( next_permutation( num.begin(), num.end() ) ) { 8 permutations.push_back( num ); 9 } 10 return permutations; 11 } 12 };
使用DFS求解。
1 class Solution { 2 public: 3 vector<vector<int>> permuteUnique( vector<int> &num ) { 4 vector<vector<int>> permutations; 5 sort( num.begin(), num.end() ); 6 PermuteSub( 0, num, permutations ); 7 return permutations; 8 } 9 private: 10 void PermuteSub( int s, vector<int> &num, vector<vector<int>> &permutations ) { 11 int size = num.size(); 12 if( s >= size-1 ) { permutations.push_back( num ); return; } 13 PermuteSub( s+1, num, permutations ); 14 for( int i = s + 1; i < size; ++i ) { 15 if( num[s] != num[i] && num[i-1] != num[i] ) { 16 swap( num[s], num[i] ); 17 PermuteSub( s+1, num, permutations ); 18 swap( num[s], num[i] ); 19 } 20 } 21 sort( num.begin()+s, num.end() ); 22 return; 23 } 24 };
标签:style blog color os 使用 io for div cti
原文地址:http://www.cnblogs.com/moderate-fish/p/3939488.html