Finding all subsets of a given set of distinct integers recursively
Given a set of distinct integers, I want to find all the possible subsets (for [1,2,3], the code should print [1], [1,2], [1,3], [1,2,3], [2], [2,3], [3]
(not necessarily in that order).
There are a few solutions (like this one) out there but what I want to do is to re-implement the bellow solution with a new recursion and no for
loop by passing around the indexes: (start = 0)
public void forSolution(List<List<Integer>> res, int nums, List<Integer> list, int start) {
for (int i = start; i < nums.length; i++) {
List<Integer> tmp = new ArrayList<>(list);
tmp.add(nums[i]);
res.add(new ArrayList<>(tmp));
forSolution(res, nums, tmp, i + 1);
}
}
I thought I need to pass two integers to the method, one for keeping the record of index and the other one for keeping the start point, but I am having problem on when I need to do the index increment (vs start increment).
Any help would be appreciated.
algorithm recursion
|
show 3 more comments
Given a set of distinct integers, I want to find all the possible subsets (for [1,2,3], the code should print [1], [1,2], [1,3], [1,2,3], [2], [2,3], [3]
(not necessarily in that order).
There are a few solutions (like this one) out there but what I want to do is to re-implement the bellow solution with a new recursion and no for
loop by passing around the indexes: (start = 0)
public void forSolution(List<List<Integer>> res, int nums, List<Integer> list, int start) {
for (int i = start; i < nums.length; i++) {
List<Integer> tmp = new ArrayList<>(list);
tmp.add(nums[i]);
res.add(new ArrayList<>(tmp));
forSolution(res, nums, tmp, i + 1);
}
}
I thought I need to pass two integers to the method, one for keeping the record of index and the other one for keeping the start point, but I am having problem on when I need to do the index increment (vs start increment).
Any help would be appreciated.
algorithm recursion
1
Possible duplicate of Generating power set recursively without any loops
– Prune
Nov 12 at 23:16
@Prune It's not really a duplicate. Please read the whole post before flagging it.
– Yar
Nov 12 at 23:25
@Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
– melpomene
Nov 12 at 23:28
@Prune I edited the question to emphasis on the difference. Basically I just want to re-implement thefor
solution by passing around the indexes.
– Yar
Nov 13 at 0:01
Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
– Ari
Nov 13 at 0:08
|
show 3 more comments
Given a set of distinct integers, I want to find all the possible subsets (for [1,2,3], the code should print [1], [1,2], [1,3], [1,2,3], [2], [2,3], [3]
(not necessarily in that order).
There are a few solutions (like this one) out there but what I want to do is to re-implement the bellow solution with a new recursion and no for
loop by passing around the indexes: (start = 0)
public void forSolution(List<List<Integer>> res, int nums, List<Integer> list, int start) {
for (int i = start; i < nums.length; i++) {
List<Integer> tmp = new ArrayList<>(list);
tmp.add(nums[i]);
res.add(new ArrayList<>(tmp));
forSolution(res, nums, tmp, i + 1);
}
}
I thought I need to pass two integers to the method, one for keeping the record of index and the other one for keeping the start point, but I am having problem on when I need to do the index increment (vs start increment).
Any help would be appreciated.
algorithm recursion
Given a set of distinct integers, I want to find all the possible subsets (for [1,2,3], the code should print [1], [1,2], [1,3], [1,2,3], [2], [2,3], [3]
(not necessarily in that order).
There are a few solutions (like this one) out there but what I want to do is to re-implement the bellow solution with a new recursion and no for
loop by passing around the indexes: (start = 0)
public void forSolution(List<List<Integer>> res, int nums, List<Integer> list, int start) {
for (int i = start; i < nums.length; i++) {
List<Integer> tmp = new ArrayList<>(list);
tmp.add(nums[i]);
res.add(new ArrayList<>(tmp));
forSolution(res, nums, tmp, i + 1);
}
}
I thought I need to pass two integers to the method, one for keeping the record of index and the other one for keeping the start point, but I am having problem on when I need to do the index increment (vs start increment).
Any help would be appreciated.
algorithm recursion
algorithm recursion
edited Nov 12 at 23:59
asked Nov 12 at 22:27
Yar
3,05012947
3,05012947
1
Possible duplicate of Generating power set recursively without any loops
– Prune
Nov 12 at 23:16
@Prune It's not really a duplicate. Please read the whole post before flagging it.
– Yar
Nov 12 at 23:25
@Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
– melpomene
Nov 12 at 23:28
@Prune I edited the question to emphasis on the difference. Basically I just want to re-implement thefor
solution by passing around the indexes.
– Yar
Nov 13 at 0:01
Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
– Ari
Nov 13 at 0:08
|
show 3 more comments
1
Possible duplicate of Generating power set recursively without any loops
– Prune
Nov 12 at 23:16
@Prune It's not really a duplicate. Please read the whole post before flagging it.
– Yar
Nov 12 at 23:25
@Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
– melpomene
Nov 12 at 23:28
@Prune I edited the question to emphasis on the difference. Basically I just want to re-implement thefor
solution by passing around the indexes.
– Yar
Nov 13 at 0:01
Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
– Ari
Nov 13 at 0:08
1
1
Possible duplicate of Generating power set recursively without any loops
– Prune
Nov 12 at 23:16
Possible duplicate of Generating power set recursively without any loops
– Prune
Nov 12 at 23:16
@Prune It's not really a duplicate. Please read the whole post before flagging it.
– Yar
Nov 12 at 23:25
@Prune It's not really a duplicate. Please read the whole post before flagging it.
– Yar
Nov 12 at 23:25
@Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
– melpomene
Nov 12 at 23:28
@Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
– melpomene
Nov 12 at 23:28
@Prune I edited the question to emphasis on the difference. Basically I just want to re-implement the
for
solution by passing around the indexes.– Yar
Nov 13 at 0:01
@Prune I edited the question to emphasis on the difference. Basically I just want to re-implement the
for
solution by passing around the indexes.– Yar
Nov 13 at 0:01
Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
– Ari
Nov 13 at 0:08
Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
– Ari
Nov 13 at 0:08
|
show 3 more comments
1 Answer
1
active
oldest
votes
I think the algorithm gets easier if you don't bother with indices.
The basic idea is that for any given sublist, each element of the original list is either included or not included. The list of all possible sublists is simply all possible combinations of including / not including each element.
For a recursive implementation, we can consider two cases:
- The input list is empty. The empty list only has a single sublist, which is the empty list itself.
The input list consists of a first element
x
and a list of remaining elementsrest
. Here we can call our function recursively to get a list of all sublists ofrest
. To implement the idea of both including and not includingx
in our results, we return a list consisting of
- each element of
sublists(rest)
withx
added at the front, representing all sublists of our original list that containx
, and - each element of
sublists(rest)
as is (withoutx
), representing all sublists of our original list that don't containx
.
- each element of
For example, if the list is [1, 2, 3]
, we have x = 1
and rest = [2, 3]
. The recursive call sublists(rest)
produces [2, 3], [2], [3],
. For each of those sublists we
- prepend
x
(which is1
), giving[1, 2, 3], [1, 2], [1, 3], [1]
, and - don't prepend
x
, giving[2, 3], [2], [3],
.
Concatenating those parts gives our total result as [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3],
.
Sample implementation:
use strict;
use warnings;
sub sublists {
if (!@_) {
return ;
}
my $x = shift @_;
my @r = sublists(@_);
return (map [$x, @$_], @r), @r;
}
for my $sublist (sublists 1, 2, 3) {
print "[" . join(", ", @$sublist) . "]n";
}
Output:
[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]
Very interesting approach! Thank you @melpomene
– Yar
Nov 12 at 23:49
You are just hiding the loop inmap
.
– n.m.
Nov 13 at 7:04
@n.m.sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () }
Now I have a recursive map.
– melpomene
Nov 13 at 8:46
Yes you can rewrite any loop to recursion...
– n.m.
Nov 13 at 10:39
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271000%2ffinding-all-subsets-of-a-given-set-of-distinct-integers-recursively%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I think the algorithm gets easier if you don't bother with indices.
The basic idea is that for any given sublist, each element of the original list is either included or not included. The list of all possible sublists is simply all possible combinations of including / not including each element.
For a recursive implementation, we can consider two cases:
- The input list is empty. The empty list only has a single sublist, which is the empty list itself.
The input list consists of a first element
x
and a list of remaining elementsrest
. Here we can call our function recursively to get a list of all sublists ofrest
. To implement the idea of both including and not includingx
in our results, we return a list consisting of
- each element of
sublists(rest)
withx
added at the front, representing all sublists of our original list that containx
, and - each element of
sublists(rest)
as is (withoutx
), representing all sublists of our original list that don't containx
.
- each element of
For example, if the list is [1, 2, 3]
, we have x = 1
and rest = [2, 3]
. The recursive call sublists(rest)
produces [2, 3], [2], [3],
. For each of those sublists we
- prepend
x
(which is1
), giving[1, 2, 3], [1, 2], [1, 3], [1]
, and - don't prepend
x
, giving[2, 3], [2], [3],
.
Concatenating those parts gives our total result as [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3],
.
Sample implementation:
use strict;
use warnings;
sub sublists {
if (!@_) {
return ;
}
my $x = shift @_;
my @r = sublists(@_);
return (map [$x, @$_], @r), @r;
}
for my $sublist (sublists 1, 2, 3) {
print "[" . join(", ", @$sublist) . "]n";
}
Output:
[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]
Very interesting approach! Thank you @melpomene
– Yar
Nov 12 at 23:49
You are just hiding the loop inmap
.
– n.m.
Nov 13 at 7:04
@n.m.sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () }
Now I have a recursive map.
– melpomene
Nov 13 at 8:46
Yes you can rewrite any loop to recursion...
– n.m.
Nov 13 at 10:39
add a comment |
I think the algorithm gets easier if you don't bother with indices.
The basic idea is that for any given sublist, each element of the original list is either included or not included. The list of all possible sublists is simply all possible combinations of including / not including each element.
For a recursive implementation, we can consider two cases:
- The input list is empty. The empty list only has a single sublist, which is the empty list itself.
The input list consists of a first element
x
and a list of remaining elementsrest
. Here we can call our function recursively to get a list of all sublists ofrest
. To implement the idea of both including and not includingx
in our results, we return a list consisting of
- each element of
sublists(rest)
withx
added at the front, representing all sublists of our original list that containx
, and - each element of
sublists(rest)
as is (withoutx
), representing all sublists of our original list that don't containx
.
- each element of
For example, if the list is [1, 2, 3]
, we have x = 1
and rest = [2, 3]
. The recursive call sublists(rest)
produces [2, 3], [2], [3],
. For each of those sublists we
- prepend
x
(which is1
), giving[1, 2, 3], [1, 2], [1, 3], [1]
, and - don't prepend
x
, giving[2, 3], [2], [3],
.
Concatenating those parts gives our total result as [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3],
.
Sample implementation:
use strict;
use warnings;
sub sublists {
if (!@_) {
return ;
}
my $x = shift @_;
my @r = sublists(@_);
return (map [$x, @$_], @r), @r;
}
for my $sublist (sublists 1, 2, 3) {
print "[" . join(", ", @$sublist) . "]n";
}
Output:
[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]
Very interesting approach! Thank you @melpomene
– Yar
Nov 12 at 23:49
You are just hiding the loop inmap
.
– n.m.
Nov 13 at 7:04
@n.m.sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () }
Now I have a recursive map.
– melpomene
Nov 13 at 8:46
Yes you can rewrite any loop to recursion...
– n.m.
Nov 13 at 10:39
add a comment |
I think the algorithm gets easier if you don't bother with indices.
The basic idea is that for any given sublist, each element of the original list is either included or not included. The list of all possible sublists is simply all possible combinations of including / not including each element.
For a recursive implementation, we can consider two cases:
- The input list is empty. The empty list only has a single sublist, which is the empty list itself.
The input list consists of a first element
x
and a list of remaining elementsrest
. Here we can call our function recursively to get a list of all sublists ofrest
. To implement the idea of both including and not includingx
in our results, we return a list consisting of
- each element of
sublists(rest)
withx
added at the front, representing all sublists of our original list that containx
, and - each element of
sublists(rest)
as is (withoutx
), representing all sublists of our original list that don't containx
.
- each element of
For example, if the list is [1, 2, 3]
, we have x = 1
and rest = [2, 3]
. The recursive call sublists(rest)
produces [2, 3], [2], [3],
. For each of those sublists we
- prepend
x
(which is1
), giving[1, 2, 3], [1, 2], [1, 3], [1]
, and - don't prepend
x
, giving[2, 3], [2], [3],
.
Concatenating those parts gives our total result as [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3],
.
Sample implementation:
use strict;
use warnings;
sub sublists {
if (!@_) {
return ;
}
my $x = shift @_;
my @r = sublists(@_);
return (map [$x, @$_], @r), @r;
}
for my $sublist (sublists 1, 2, 3) {
print "[" . join(", ", @$sublist) . "]n";
}
Output:
[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]
I think the algorithm gets easier if you don't bother with indices.
The basic idea is that for any given sublist, each element of the original list is either included or not included. The list of all possible sublists is simply all possible combinations of including / not including each element.
For a recursive implementation, we can consider two cases:
- The input list is empty. The empty list only has a single sublist, which is the empty list itself.
The input list consists of a first element
x
and a list of remaining elementsrest
. Here we can call our function recursively to get a list of all sublists ofrest
. To implement the idea of both including and not includingx
in our results, we return a list consisting of
- each element of
sublists(rest)
withx
added at the front, representing all sublists of our original list that containx
, and - each element of
sublists(rest)
as is (withoutx
), representing all sublists of our original list that don't containx
.
- each element of
For example, if the list is [1, 2, 3]
, we have x = 1
and rest = [2, 3]
. The recursive call sublists(rest)
produces [2, 3], [2], [3],
. For each of those sublists we
- prepend
x
(which is1
), giving[1, 2, 3], [1, 2], [1, 3], [1]
, and - don't prepend
x
, giving[2, 3], [2], [3],
.
Concatenating those parts gives our total result as [1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3],
.
Sample implementation:
use strict;
use warnings;
sub sublists {
if (!@_) {
return ;
}
my $x = shift @_;
my @r = sublists(@_);
return (map [$x, @$_], @r), @r;
}
for my $sublist (sublists 1, 2, 3) {
print "[" . join(", ", @$sublist) . "]n";
}
Output:
[1, 2, 3]
[1, 2]
[1, 3]
[1]
[2, 3]
[2]
[3]
answered Nov 12 at 23:08
melpomene
58.2k54489
58.2k54489
Very interesting approach! Thank you @melpomene
– Yar
Nov 12 at 23:49
You are just hiding the loop inmap
.
– n.m.
Nov 13 at 7:04
@n.m.sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () }
Now I have a recursive map.
– melpomene
Nov 13 at 8:46
Yes you can rewrite any loop to recursion...
– n.m.
Nov 13 at 10:39
add a comment |
Very interesting approach! Thank you @melpomene
– Yar
Nov 12 at 23:49
You are just hiding the loop inmap
.
– n.m.
Nov 13 at 7:04
@n.m.sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () }
Now I have a recursive map.
– melpomene
Nov 13 at 8:46
Yes you can rewrite any loop to recursion...
– n.m.
Nov 13 at 10:39
Very interesting approach! Thank you @melpomene
– Yar
Nov 12 at 23:49
Very interesting approach! Thank you @melpomene
– Yar
Nov 12 at 23:49
You are just hiding the loop in
map
.– n.m.
Nov 13 at 7:04
You are just hiding the loop in
map
.– n.m.
Nov 13 at 7:04
@n.m.
sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () }
Now I have a recursive map.– melpomene
Nov 13 at 8:46
@n.m.
sub mymap { my $f = shift; @_ ? ($f->(shift), mymap($f, @_)) : () }
Now I have a recursive map.– melpomene
Nov 13 at 8:46
Yes you can rewrite any loop to recursion...
– n.m.
Nov 13 at 10:39
Yes you can rewrite any loop to recursion...
– n.m.
Nov 13 at 10:39
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271000%2ffinding-all-subsets-of-a-given-set-of-distinct-integers-recursively%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Possible duplicate of Generating power set recursively without any loops
– Prune
Nov 12 at 23:16
@Prune It's not really a duplicate. Please read the whole post before flagging it.
– Yar
Nov 12 at 23:25
@Yar It's an exact duplicate (except your input is a list of integers, not a string of characters). The algorithms are exactly the same.
– melpomene
Nov 12 at 23:28
@Prune I edited the question to emphasis on the difference. Basically I just want to re-implement the
for
solution by passing around the indexes.– Yar
Nov 13 at 0:01
Check method 2 in this link: geeksforgeeks.org/recursive-program-to-generate-power-set
– Ari
Nov 13 at 0:08