-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode Problem 46 Permutations.txt
58 lines (44 loc) · 1.2 KB
/
Leetcode Problem 46 Permutations.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
46. Permutations
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Hint to solve: Use recrusive function. Create a copy of new list and current list.
Time and space complexity : n!
public class Solution
{
public IList<IList<int>> result;
public Solution()
{
result = new List<IList<int>>();
}
public void PermuteRecursive(List<int> currentList, List<int> remainingList)
{
if(remainingList.Count() == 0)
{
result.Add(currentList);
return;
}
for(int i = 0; i<remainingList.Count(); ++i)
{
List<int> tempCurrent = new List<int>(currentList);
tempCurrent.Add(remainingList[i]);
List<int> tempRemaining = new List<int>(remainingList);
tempRemaining.RemoveAt(i);
PermuteRecursive(tempCurrent, tempRemaining);
}
}
public IList<IList<int>> Permute(int[] nums)
{
PermuteRecursive(new List<int>(), nums.ToList());
return result;
}
}