Skip to content

Commit b7cc831

Browse files
committed
permutations
1 parent e520baf commit b7cc831

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed

20. Valid Parentheses.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
bool isValid(string s) {
4+
stack<char> q;
5+
6+
for(int i = 0;i<s.length(); ++i) {
7+
if(s[i] == '(' || s[i] == '{' || s[i] == '[')
8+
q.push(s[i]);
9+
10+
else if(s[i] == ')') {
11+
if(q.empty() || q.top() != '(')
12+
return false;
13+
14+
q.pop();
15+
}
16+
else if(s[i] == '}') {
17+
if(q.empty() || q.top() != '{')
18+
return false;
19+
20+
q.pop();
21+
}
22+
else if(s[i] == ']') {
23+
if(q.empty() || q.top() != '[')
24+
return false;
25+
26+
q.pop();
27+
}
28+
}
29+
30+
if(!q.empty())
31+
return false;
32+
33+
return true;
34+
35+
}
36+
};

31. Next Permutation.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
void nextPermutation(vector<int>& nums) {
4+
5+
if(nums.empty())
6+
return;
7+
8+
if(nums.size() == 2) {
9+
swap(nums[0],nums[1]);
10+
return;
11+
}
12+
13+
int i;
14+
for(i = nums.size()-2;i>=0;i--) {
15+
if(nums[i] < nums[i+1]) {
16+
break;
17+
}
18+
}
19+
reverse(nums.begin() + i+ 1, nums.end());
20+
if(i == -1)
21+
return;
22+
auto nexthigh = upper_bound(nums.begin() + i + 1, nums.end(), nums[i]);
23+
// cout << *nexthigh;
24+
swap(nums[i], *nexthigh);
25+
26+
// sort(++nexthigh, nums.end());
27+
28+
29+
}
30+
};

46. Permutations.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
void perm(vector<int> &nums, vector<int> &row,vector<vector<int> > &result, int k) {
3+
if (k == nums.size()-1) {
4+
row = nums;
5+
result.push_back(row);
6+
return ;
7+
}
8+
9+
for(int i = k; i<nums.size();++i) {
10+
swap(nums[i],nums[k]);
11+
perm(nums,row,result,k+1);
12+
swap(nums[i],nums[k]);
13+
}
14+
}
15+
16+
class Solution {
17+
public:
18+
vector<vector<int>> permute(vector<int>& nums) {
19+
20+
vector<int> row;
21+
vector<vector<int> > result;
22+
perm(nums,row,result,0);
23+
return result;
24+
}
25+
};

0 commit comments

Comments
 (0)